放置新和删除 [英] placement new and delete

查看:114
本文介绍了放置新和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 em>运算符中接收到的 运算符。如果直接调用 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.

这篇关于放置新和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆