为什么C++ std::list::clear() 不调用析构函数
Why is C++ std::list::clear() not calling destructors?
看看这段代码:
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
"真实"元素,而不是指向元素的指针,你就不会有这个问题。
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常