这很可能是一个非常愚蠢/基本的问题,但我无法弄清楚。我会告诉你我的想法 - 如果/我错了,请纠正我。
当我们使用 STL 容器来存储原始指针时,我们必须注意清理它们:
std::list<animal*> alist;
animal *a = new animal();
alist.push_back(a);
...
animal *b = alist.front();
alist.pop_front();
//do stuff with b
delete b;
如果我们存储对象会发生什么?我的理解是,如果一个装满对象的容器超出范围,则其中的所有对象都会被销毁。正确的?
但是如果我们从容器中移除一个对象,std::list<T>.pop_front()
例如使用呢?
std::list<animal> alist;
{
animal ani();
//ani is inserted at the end of the list (it IS ani rather than a copy
//since push_back accepts const T&)
alist.push_back(ani);
} //nothing is deallocated/destroyed here
...
{
animal b = alist.front(); //b is now a copy(?!) of the front element
//created via copy constructor
alist.pop_front(); //the front element of the list is
//destroyed/destructor is called
//do stuff with b
} //b goes out of scope