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
- 总计将在节日礼物上花多少钱 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++多态 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- C语言数组 1970-01-01
- C语言3个整数的数组 1970-01-01
