放置新建和删除

2021-12-22 00:00:00 visual-c++ c++ new-operator placement

删除这里分配的所有内存的正确方法是什么?

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;

  const char* charString = "Hello, World";
  void *mem = ::operator new(sizeof(Buffer) + strlen(charString) + 1);
  Buffer* buf = new(mem) Buffer(strlen(charString));

  delete buf;

还是两者都一样?

推荐答案

正确的方法是:

buf->~Buffer();
::operator delete(mem);

您只能使用 delete operator 删除您从 new operator 收到的内容.如果直接调用operator new函数,也必须直接调用operator delete函数,并且必须手动调用析构函数.

You can only delete with the delete operator what you received from the new operator. If you directly call the operator new function, you must also directly call the operator delete function, and must manually call the destructor as well.

相关文章