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

dan*_*aze 6 c++ destructor list 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;
}
Run Code Online (Sandbox Code Playgroud)

然后,看看这个输出:

    Constructor
    Destructor
    Contructor
    1
    0
Run Code Online (Sandbox Code Playgroud)

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

Cra*_*sta 12

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