是否可以删除非新对象? [英] Is it possible to delete a non-new object?

查看:143
本文介绍了是否可以删除非新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象与指向其他对象的指针的向量,像这样:

I have an object with a vector of pointers to other objects in it, something like this:

class Object {
    ...
    vector<Object*> objlist;
    ...
};

现在,对象将以这两种方式添加到列表中:

Now, Objects will be added to list in both of these ways:

Object obj;
obj.objlist.push_back(new Object);

Object name;
Object* anon = &name;
obj.objlist.push_back(anon);

如果一个简单的析构函数

If a make a destructor that is simply

~Object {
    for (int i = 0; i < objlist.size(); i++) {
        delete objlist[i];
        objlist[i] = NULL;
    }
}

尝试删除不是用新建的对象?

Will there be any adverse consequences in terms of when it tries to delete an object that was not created with new?

推荐答案

是的,会有不利影响。

您不能删除未分配 new 的对象。如果对象在堆栈上分配,则编译器已经在其作用域的末尾生成了对其析构函数的调用。这意味着你将调用析构函数两次,可能有非常糟糕的效果。

You must not delete an object that was not allocated with new. If the object was allocated on the stack, your compiler has already generated a call to its destructor at the end of its scope. This means you will call the destructor twice, with potentially very bad effects.

除了调用析构函数两次,你还将尝试释放一个内存块从未分配。 new 运算符可能将对象放在堆上; delete 期望在同一区域中找到对象, new 操作符将它们​​放置。但是,未分配 new 的对象会存在于堆栈中。这将非常可能会崩溃你的程序(如果它第二次调用析构函数后还没有崩溃)。

Besides calling the destructor twice, you will also attempt to deallocate a memory block that was never allocated. The new operator presumably puts the objects on the heap; delete expects to find the object in the same region the new operator puts them. However, your object that was not allocated with new lives on the stack. This will very probably crash your program (if it does not already crash after calling the destructor a second time).

如果你的 Object 比堆栈上的 Object 长得多,你会得到一个悬在堆栈上的地方,并且在下次访问它时会得到不正确的结果/崩溃。

You'll also get in deep trouble if your Object on the heap lives longer than your Object on the stack: you'll get a dangling reference to somewhere on the stack, and you'll get incorrect results/crash the next time you access it.

我看到的一般规则是,生活在堆栈中的东西可以引用堆,但是堆上的东西不应该引用堆栈上的东西,因为他们很有可能超过堆栈对象。并且两者的指针不应混合在一起。

The general rule I see is that stuff that live on the stack can reference stuff that lives on the heap, but stuff on the heap should not reference stuff on the stack because of the very high chances that they'll outlive stack objects. And pointers to both should not be mixed together.

这篇关于是否可以删除非新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆