为什么 C++ std::list::clear() 不调用析构函数?
-
11-12-2019 - |
题
看这段代码:
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
如果使用“真实”元素,而不是指向元素的指针,则不会出现此问题。
不隶属于 StackOverflow