我使用「放置新」來分配我的對象。我使用三種記憶清除方式。他們都是安全的嗎?我可以得到內存泄漏嗎?我使用三種內存清除方式。他們都是安全的嗎?我可以得到內存泄漏嗎?
#include <iostream>
#include <exception>
#include <vector>
using namespace ::std;
class A{
private:
double x;
public:
A() : x(0) { cout << "A class; ptr: " << this << " created." << endl; }
~A() { cout << "A class; ptr: " << this << " destroyed." << endl; }
};
int main(int argc, char* argv[])
try{
// 1. Creating of object in the necessary memory address
static_assert(sizeof(char) == 1, "Unexpected size of char.");
int x = -1; // Variants of memory clearing
while (x < 0 || x > 2) {
cout << "Variant (0,1,2): ";
cin >> x;
}
char* p = new char[sizeof(A)]; // some memory area...
A* a = new(p)A(); // Place my object in the 'p' address.
// Here is my basic work to do...
// Now I must to free my memory:
if(!x){ // First variant
delete a;
}
else if (x == 1){ // Second variant
delete reinterpret_cast<A*>(p);
}
else if (x == 2){ // Third variant
a->~A();
delete[] p;
}
else{
throw runtime_error("Invalid variant!");
}
a = nullptr;
p = nullptr;
cout << endl;
}
catch(exception& e){
cerr << e.what() << endl;
return 1;
}
catch(...){
cerr << "Unknown exception." << endl;
return 2;
}
謝謝。
當你的問題簡單地重複標題時,它通常意味着你沒有足夠的描述:p可能解釋你的三個變體(我知道你的代碼很短,但仍然有幫助) – keyser
你應該**永遠不會* *明確地調用析構函數!當實例超出範圍或調用delete時,它們將自動調用。 –
''char'需要1個字節長的標準,斷言是多餘的。 – 2013-10-04 13:19:24