我使用“放置新”来分配我的对象。我使用三种记忆清除方式。他们都是安全的吗?我可以得到内存泄漏吗?我使用三种内存清除方式。他们都是安全的吗?我可以得到内存泄漏吗?
#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