此代码在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++
}
最佳答案
您应该手动为所有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
}
关于c++ - 在Linux中,删除[]失败,无法放置新对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35403242/