什么时候使用“删除"? [英] When to use "delete"?

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

问题描述

我想在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天全站免登陆