placement

placement new and delete

守給你的承諾、 提交于 2019-11-26 18:30:36
What is the right method to delete all the memory allocated here? 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 const char* charString = "Hello, World"; void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1); Buffer* buf = new(mem) Buffer(strlen(charString)); delete buf; or are they both same? The correct method is: buf->~Buffer(); ::operator delete(mem); You can only delete with the delete operator what you received from the new operator . If

placement new and delete

北慕城南 提交于 2019-11-26 06:19:47
问题 What is the right method to delete all the memory allocated here? 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 const char* charString = \"Hello, World\"; void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1); Buffer* buf = new(mem) Buffer(strlen(charString)); delete buf; or are they both same? 回答1: The correct method is: buf->~Buffer(); :