placement new
时间: 2023-09-24 09:06:24 浏览: 131
placement new详解
Placement new is a C++ operator that allows objects to be constructed at a specific memory location. It is useful when working with memory that has already been allocated, such as when working with memory pools, custom allocators, or when dealing with objects that need to be constructed in shared memory or in a specific memory region.
The syntax for placement new operator is:
```
void* operator new (size_t size, void* ptr) throw();
```
Here, size_t is the size of the object to be constructed, and void* ptr is the memory location where the object should be constructed. The operator returns a pointer to the constructed object.
To use placement new, one should allocate memory for the object, and then use placement new to construct the object in that memory. For example:
```
void* mem = malloc(sizeof(MyClass));
MyClass* obj = new (mem) MyClass();
```
Here, we allocate memory for an object of type MyClass using malloc, and then use placement new to construct the object in that memory location using the constructor of MyClass.
It is important to note that when using placement new, the memory should be properly aligned and deallocated using the corresponding deallocation function. In the above example, we should call the destructor of MyClass to properly deallocate the memory:
```
obj->~MyClass();
free(mem);
```
阅读全文