我有一个问题,但在任何地方都找不到答案。但是,我必须显示一些代码:
#include "Vector2D"
class something
{
Vector2D * p_Position;
public:
something(){p_Position = new Vector2D;}
~something(){delete p_Position;}
};
int main()
{
std::list<something> Somethinglist;
Somethinglist.push_back(something());
Somethinglist.clear();
return 0;
}
因此,当涉及到 .clear()
函数时,这将导致断言失败。所以我尝试了一些东西。首先,如果我不将 delete p_Position
放入析构函数中,则此代码完全有效。这是为什么? STL list .clear()
函数是否自动销毁动态指针?或者一个相当直接的问题:我该如何修复这段代码?
最佳答案
std::list::push_back()
按值获取其参数(即生成拷贝),这是一个真正的问题,因为您没有遵循 Rule of Three .
关于c++ - 删除包含动态指针的 STL::list<class something> 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17499822/