stl容器如何被删除?
stl中的vector之类的容器对象如何被销毁,即使它们是在堆中创建的?
How does container object like vector in stl get destroyed even though they are created in heap?
编辑
如果容器持有指针,那么如何销毁这些指针对象
If the container holds pointers then how to destroy those pointer objects
推荐答案
指针的 STL 容器不会清理指向的数据.它只会清理保存指针的空间.如果你想让向量清理指针数据,你需要使用某种智能指针实现:
An STL container of pointer will NOT clean up the data pointed at. It will only clean up the space holding the pointer. If you want the vector to clean up pointer data you need to use some kind of smart pointer implementation:
{
std::vector<SomeClass*> v1;
v1.push_back(new SomeClass());
std::vector<boost::shared_ptr<SomeClass> > v2;
boost::shared_ptr<SomeClass> obj(new SomeClass);
v2.push_back(obj);
}
当该作用域结束时,两个向量都将释放它们的内部数组.v1 将泄漏创建的 SomeClass,因为数组中只有指向它的指针.v2 不会泄露任何数据.
When that scope ends both vectors will free their internal arrays. v1 will leak the SomeClass that was created since only the pointer to it is in the array. v2 will not leak any data.
相关文章