在閱讀放置新操作員時發現以下代碼。刪除內部或外部的位置刪除
#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();
}
我不得不刪除其使用放置新創建的對象相關的幾個問題:
- 什麼是清理代碼需要在析構函數寫爲這是在被佔領的OBJ 可用內存緩衝存儲器。
- 是否需要定義放置刪除,如果是,是否需要在析構函數內或析構函數外。如果它在析構函數外部如何被調用?
你只需要顯式調用析構函數。沒有任何地點刪除。 (但請注意,如果底層緩衝區已分配,則可能需要刪除..) – 2014-09-22 16:25:34
閱讀發佈代碼末尾的兩行註釋 – 2014-09-22 16:26:28
沒有放置 - 刪除 – CashCow 2014-09-22 16:33:54