何时使用“删除"? [英] When to use "delete"?

查看:50
本文介绍了何时使用“删除"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 objList 中存储 10 个 Obj 对象,但我不知道在这种情况下何时适合使用 delete.如果我在下面代码中注释的行中使用 delete Obj;Obj 是否仍会存储在 objList 中?

I want to store 10 Obj object in objList, but i don't know when is appropriate use delete in this case. If i use delete Obj; in the line where i note in below code, will the Obj still be stored in objList?

struct Obj {
    int u;
    int v;
};

vector<Obj> objList;

int main() {
    for(int i = 0; i < 10; i++) {
        Obj *obj = new Obj();
        obj->u = i;
        obj->v = i + 1;
        objList.push_back(*obj);
        // Should i use "delete Obj;" here? 
    }
}

推荐答案

您在堆上使用 new 创建的任何对象都需要通过 delete 清除.在您的代码中,您实际上是在您的集合中存储了一个副本.

Any object you create on the heap with new needs to be cleared up by delete. In your code, you are actually storing a copy in your collection.

objList.push_back(*Obj);

这一行正在逐步做的是:

What this line is doing step by step is:

  1. 间接指向底层堆内存Obj占用的指针(返回对象Obj)
  2. 调用复制构造函数创建临时副本
  3. 在集合中存储临时副本

您不需要在堆上创建这个初始 Obj,正如@Luchian Grigore 指出的那样,分配给本地的堆栈就足够了.

You do not need to create this initial Obj on the heap, a stack allocated local will suffice as @Luchian Grigore has pointed out.

Obj obj;
objList.push_back(obj);

你不需要对集合中的副本调用delete,当你移除元素时,STL集合会自己处理这块内存,但你仍然需要删除原来的堆分配对象.

You do not need to call delete on the copy in the collection, the STL collection will handle this memory itself when you remove the element, but you still will need to delete the original heap allocated object.

如果您通过 std::shared_ptr 存储对象会更好.这样,当对 Obj 的所有引用都被删除时,将调用 delete.

It would be better if you stored your objects by std::shared_ptr. That way delete would be called when all references to the Obj were removed.

std::vector< std::shared_ptr< Obj > > vec;
vec.push_back( std::make_shared( new Obj() ) );

这篇关于何时使用“删除"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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