How do stl containers get deleted?(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容器如何被删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:stl容器如何被删除?


基础教程推荐
- 初始化变量和赋值运算符 1970-01-01
- C++按值调用 1970-01-01
- C语言访问数组元素 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++ #define 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++定义类对象 1970-01-01