删除 [] 在 Linux 中放置新对象失败
delete [] fails in Linux for placement new Objects
此代码在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
}
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 是什么让放置新调用对象的构造函数?
- 放置派生C++的新基子对象
- 重用对象与创建新对象
- 为指向C++中的对象/对象的指针分配堆内存
- thread_local 和 std::future 对象 - 对象的生存期是多少
- 使用矢量中的现有对象,如果C++中不存在,则创建新的对象
- 如何删除分配了新的对象
- C 将HEAP对象插入std ::用insert()插入映射,而另一个则存在删除新的对象
- 使用新的对象
- 使用C++0x std::thread调用新ed对象中的成员函数
- 新的新类对象的函数;错误:非静态成员引用必须相对于特定对象
- C++ 没有新返回对象的算术运算符
- 如何在每次迭代中创建一个新变量/对象的循环
- 如何在Cython中返回新的c++对象
- 如何在不'new'的情况下将新的对象实例添加到 std::list
- 使用“放置新”转移对象所有权
- 将两个复杂的属性重新组合成新的对象