Home >Backend Development >C++ >When Using Placement New, Does `delete` Actually Deallocate Correctly?
Placement New and Delete
In C , operator overloading allows the use of custom new and delete operators. However, this raises the question of how to correctly deallocate memory allocated with such operators. Consider the following code snippet:
<code class="cpp">const char* charString = "Hello, World"; void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1); Buffer* buf = new(mem) Buffer(strlen(charString)); delete (char*)buf; // OR delete buf;</code>
Delegating the task of memory deallocation to the overloaded delete operator (direct method) seems logical. However, this approach is incorrect.
Correct Method
The correct way to deallocate memory in this case is by explicitly calling the destructor for the object, followed by the operator delete function to release the allocated memory:
<code class="cpp">buf->~Buffer(); ::operator delete(mem);</code>
Explanation
When using the placement new operator, which takes a pre-allocated memory address, the default constructor is not called automatically. Therefore, it's crucial to manually call the destructor. Alternatively, calling delete buf directly is also incorrect as it only calls the global operator delete, which does not know about the placement new allocation.
When to Use Buf->~Buffer()
The destructor call (buf->~Buffer()) is required whenever the placement new operator is used, even when the ::operator delete function is subsequently called.
Best Practice
To avoid confusion, always use a matching pair of operators, such as:
The above is the detailed content of When Using Placement New, Does `delete` Actually Deallocate Correctly?. For more information, please follow other related articles on the PHP Chinese website!