简体   繁体   English

删除列表中创建的对象

[英]Delete created Objects inside List

I'm creating some Objects inside a loop and add it to a listwith: 我在循环内创建一些对象,并将其添加到列表中:

list<MyObject> myList;    
MyObject* ob = new MyObject();
ob.setAttribute("whatever");
myList.push_back(*ob);

After the loop finishes, I'm using the list several times. 循环结束后,我将多次使用该列表。 I've started now a Leak Detector and saw, that I've to delete all the MyObject objects. 现在,我开始了一个检漏仪,发现我必须删除所有MyObject对象。

How I delete them properly (In the destructor?). 我如何正确删除它们(在析构函数中?)。 Should I use a iterator? 我应该使用迭代器吗? But how I get the real object - and not the iterator pointer? 但是我如何获得真实的对象-而不是迭代器指针?

Thanks a lot. 非常感谢。

There's absolutely no reason for dynamic allocation here, since the list stores objects by value. 这里绝对没有理由进行动态分配,因为列表按值存储对象。 All you're doing is copying and discarding a dynamic object; 您要做的就是复制和丢弃动态对象。 it's leaked immediately since you don't keep a pointer to it anywhere. 因为您在任何地方都没有指向它的指针,所以它立即被泄漏。 Just push objects directly, copying a temporary or automatic variable if necessary: 只需直接推送对象,并在必要时复制临时或自动变量:

list<MyObject> myList;    
MyObject ob;
ob.setAttribute("whatever");
myList.push_back(ob);

If you did need to store pointers, perhaps for polymorphism, then you'd use smart pointers to avoid leaks: 如果确实需要存储指针(可能是多态性),则可以使用智能指针来避免泄漏:

list<std::unique_ptr<MyBase>> myList;
std::unique_ptr<MyObject> ob(new MyObject);
ob->setAttribute("whatever");
myList.push_back(ob);

If you really want to juggle raw pointers for some reason, then yes, you will have to delete them yourself. 如果您确实出于某种原因想要处理原始指针,那么可以,您必须自己删除它们。 You really shouldn't try to do that. 您真的不应该尝试这样做。

You don't need to delete them, they're copied when added into the list by push_back() . 您不需要删除它们,它们是通过push_back()添加到列表中时复制的。 But, you need to delete ob after you used it. 但是,使用完后需要删除ob Such as: 如:

list<MyObject> myList;    
MyObject* ob = new MyObject();
ob.setAttribute("whatever");
myList.push_back(*ob);
delete ob;

Basically, you don't need to use pointer here, you can just declare ob in stack to avoiding the manual memory management: 基本上,您无需在此处使用指针,只需在堆栈中声明ob即可避免手动进行内存管理:

list<MyObject> myList;    
MyObject ob;
ob.setAttribute("whatever");
myList.push_back(ob);

And, according to your program's requirment, you can use some kind of smart point to avoiding such manual memory management, such as: 并且,根据您程序的要求,您可以使用某种智能点来避免这种手动内存管理,例如:

list<std::shared_ptr<MyObject>> myList;    
myList.push_back(new MyObject);
...
// don't need to delete them manually

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM