delete []在Linux中无法放置新对象

时间:2016-02-15 06:59:36

标签: c++ linux visual-studio-2010 placement-new

此代码在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++
}

1 个答案:

答案 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
}