内存管理+容器

时间:2010-07-28 11:35:59

标签: c++

朋友

容器具有自动内存管理机制。 使用复制构造函数插入值时,删除值时,将为每个值调用析构函数。 在读取了没有元素之后,会调用哪个阶段的desctuctor?

当读取元素时,容器类如何处理内存?

非常感谢

3 个答案:

答案 0 :(得分:2)

  

当读取元素时,容器类如何处理内存?

没有。没有内存处理要做。

创建对象时,必须为它们分配内存,当它们被销毁时,必须释放内存。

当您读取现有元素时,您不会创建或销毁任何元素,因此容器不需要执行任何操作。

答案 1 :(得分:1)

容器没有内存管理,对象有内存管理。

obj a;
{
    std::vector<obj> b;
    b.push_back( a );//copy of 'a' taken here
}//copy of 'a' in vector destructed here because the copy goes out of scope not specifically the vector

//'a' still exists

替代地

obj* a = new obj;
{
    std::vector<obj*> b;
    b.push_back( a );
    b.push_back( new obj );//pointer of type obj taken here
}//obj destructor not called
//got a memory leak as the obj created still exists but has no reference
delete a;//but can still delete a

答案 2 :(得分:0)

当您明确擦除元素以及容器超出范围时,容器中的对象将被破坏。

相关问题