删除 [] 在 Linux 中放置新对象失败

delete [] fails in Linux for placement new Objects

本文关键字:新对象 对象 失败 Linux 删除      更新时间:2023-10-16

此代码在VS2010中传递,但将运行时错误作为g++编译器的分段错误。

我知道我们不应该将delete用于由 placement new 实例化的对象。

请解释它在VS2010中是如何工作的。

如果我使用 delete xpxp->~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
}