此代码在VS2010中传递,但是使用g ++编译器将分段错误作为运行时错误。
我知道我们不应该将delete
用于placement new
实例化的对象。
请解释它在VS2010中的工作原理。
如果我使用delete xp
或xp->~X()
(只能删除一个对象),程序将在两个平台上成功运行。
请提供删除对象数组的解决方案。
class X {
int i;
public:
X()
{
cout << "this = " << this << endl;
}
~X()
{
cout << "X::~X(): " << this << endl;
}
void* operator new(size_t, void* loc)
{
return loc;
}
};
int main()
{
int *l = new int[10];
cout << "l = " << l << endl;
X* xp = new (l) X[2]; // X at location l
delete[] xp;// passes in VS2010, but gives segmenatation fault with g++
}
答案 0 :(得分:0)
您应该手动为所有X对象调用析构函数,然后删除原始缓冲区
int main() {
int *l = new int[10]; // allocate buffer
X* xp = new (l) X[2]; // placement new
for (size_t idx = 0; idx < 2; ++idx) {
xp[idx]->~X(); // call destructors
}
delete[] l; // deallocate buffer
}