【发布时间】:2014-11-16 16:32:08
【问题描述】:
我在阅读placement new operator时发现了以下代码。
#include <iostream>
using namespace std;
class MyClass {
public:
// Placement new operator
void* operator new (size_t sz, void* v) {
cout << "Placement new invoked" << endl;
return v;
}
~MyClass() {
// Cleanup
}
};
int main()
{
// Create a buffer to store the object
int buffer[16];
cout << "Starting address of my buffer = " << &buffer << endl;
// Create the object. Use placement new
MyClass* obj = new (buffer) MyClass();
cout << "Location of my object = " << obj << endl;
// Don't delete object created with placement delete
// Call the destructor explicitly
obj->~MyClass();
}
我有几个关于删除使用placement new 创建的对象的问题:
- 什么是清理代码需要写在析构函数中才能 缓冲内存中被 obj 占用的空闲内存。
- 是否不需要定义放置删除,如果是,是否需要在析构函数内部或析构函数外部。如果它在析构函数之外,它将如何被调用?
【问题讨论】:
-
你只需要显式调用析构函数。没有放置删除。 (但请注意,如果分配了底层缓冲区,则可能需要删除..)
-
阅读贴出代码末尾的两行注释
-
没有放置删除之类的东西
-
@CashCow 有,但这里不相关。
标签: c++