为什么C ++ std :: list :: clear()没有调用析构函数?

时间:2012-09-30 22:13:31

标签: c++ list destructor clear

看看这段代码:

class test
{
    public:
        test() { cout << "Constructor" << endl; };
        virtual ~test() { cout << "Destructor" << endl; };
};

int main(int argc, char* argv[])
{
    test* t = new test();
    delete(t);
    list<test*> l;
    l.push_back(DNEW test());
    cout << l.size() << endl;
    l.clear();
    cout << l.size() << endl;
}

然后,看看这个输出:

    Constructor
    Destructor
    Contructor
    1
    0

问题是:为什么列表元素的析构函数没有在l.clear()调用?

2 个答案:

答案 0 :(得分:12)

你的清单是指针。指针没有析构函数。如果你想要调用析构函数,你应该尝试list<test>

答案 1 :(得分:3)

使用delete释放指针或使用抽象的东西(例如智能指针或指针容器)的更好的替代方法是直接在堆栈上创建对象。

你应该更喜欢test t;而不是test * t = new test();你很少想要处理任何拥有资源的智能或其他指针。

如果您使用std::list'真实'元素,而不是指向元素的指针,则不会出现此问题。

相关问题