stl容器如何被删除? [英] How do stl containers get deleted?

查看:21
本文介绍了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.

这篇关于stl容器如何被删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆