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

Why is C++ std::list::clear() not calling destructors?

本文关键字:调用 析构函数 clear C++ std list 为什么      更新时间:2023-10-16

看看这段代码:

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()时不调用列表元素的析构函数?

你的列表是指针。指针没有析构函数。如果要调用析构函数,则应改为尝试list<test>

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

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

如果你使用std::list"真实"元素,而不是指向元素的指针,你就不会有这个问题。