Destructor在将对象添加到std :: list时调用它 [英] Destructor called on object when adding it to std::list

查看:173
本文介绍了Destructor在将对象添加到std :: list时调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Foo对象,和一个std ::列举它的实例。我的问题是,当我添加一个新的实例到列表,它首先调用ctor,但也调用dtor。然后在另一个实例上的dtor(根据this指针)。

I have a Foo object, and a std::list holding instances of it. My problem is that when I add a new instance to the list, it first calls the ctor but then also the dtor. And then the dtor on another instance (according to the this pointer).

单个实例被添加到列表,但是因为它的dtor

A single instance is added to the list but since its dtor (along with its parents) is called, the object cant be used as expected.

需要一些简化的代码来说明问题:

Heres some simplified code to illustrate the problem:

#include <iostream>
#include <list>

class Foo
{
public:
    Foo()
    { 
        int breakpoint = 0;
    }
    ~Foo()
    { 
        int breakpoint = 0;
    }
};

int main()
{
    std::list<Foo> li;
    li.push_back(Foo());
}


推荐答案

Foo对象,对象被复制到列表的内部数据结构,因此调用另一个实例的Dtor和Ctor。

When you push_back() your Foo object, the object is copied to the list's internal data structures, therefore the Dtor and the Ctor of another instance are called.

C ++中的STL容器类型按值处理它们的项目,因此根据需要复制它们。例如,当向量需要增长时,向量中的所有值都可能被复制。

All standard STL container types in C++ take their items by value, therefore copying them as needed. For example, whenever a vector needs to grow, it is possible that all values in the vector get copied.

也许你想存储指针而不是列表中的对象。通过这样做,只有指针被复制而不是对象。但是,通过这样做,你必须确保删除对象一旦你完成:

Maybe you want to store pointers instead of objects in the list. By doing that, only the pointers get copied instead of the object. But, by doing so, you have to make sure to delete the objects once you are done:

for (std::list<Foo*>::iterator it = list.begin(); it != list.end(); ++it) {
    delete *it;
}
list.clear();

或者,您可以尝试使用某种智能指针类,例如从Boost图书馆。

Alternatively, you can try to use some kind of 'smart pointer' class, for example from the Boost libraries.

这篇关于Destructor在将对象添加到std :: list时调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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