placement new and delete Conundrum
In C , when allocating memory with the placement new operator, a dilemma arises regarding the appropriate method for deallocating that memory. Let's explore two potential solutions:
Solution 1:
const char* charString = "Hello, World";
void *mem = ::operator new(sizeof(Buffer) strlen(charString) 1);
Buffer* buf = new(mem) Buffer(strlen(charString));
delete (char*)buf;
This solution attempts to delete the allocated memory as a character pointer. However, this approach is incorrect because it does not properly handle the object's destructor or deallocate the raw memory.
Solution 2:
const char* charString = "Hello, World";
void *mem = ::operator new(sizeof(Buffer) strlen(charString) 1);
Buffer* buf = new(mem) Buffer(strlen(charString));
delete buf;
This solution also attempts to delete the allocated memory, but directly calls the delete operator on the Buffer* pointer. This would work if the memory was allocated using the regular new operator. However, since placement new was used, this approach is incorrect as well.
Correct Solution:
The correct method for freeing the allocated memory is:
buf->~Buffer();
::operator delete(mem);
This solution explicitly calls the destructor for the Buffer object (buf->~Buffer()) and then deallocates the raw memory using the operator delete function (::operator delete(mem)).
The critical distinction here is that when using placement new, the operator delete function must be directly called to free the raw memory. Attempting to delete the pointer obtained from the placement new operator will not properly invoke the destructor or deallocate the memory entirely.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3