STL容器,从两个容器中删除对象

时间:2010-08-19 18:17:17

标签: c++ stl map containers

假设我有两个容器,它们持有指向对象的指针,这些指针共享一些元素。 从 http://www.cplusplus.com/reference/stl/list/erase/ 它说:

  

这有效地减少了列表大小   按删除的元素数量,   调用每个元素的析构函数   之前。

如何在不调用析构函数两次的情况下从两个容器中删除对象:

例如

#include <map>
#include <string>
using namespace std;
//to lazy to write a class 
struct myObj{
          string pkid;
          string data;
};
map<string,*myObj> container1;
map<string,*myObj> container2;

int main()
{
       myObj * object = new myObj();
       object->pkid="12345";
       object->data="someData";
       container1.insert(object->pkid,object);
       container2.insert(object->pkid,object);

       //removing object from container1
       container1.erase(object->pkid);
       //object descructor been called and container2 now hold invalid pointer

       //this will call try to deallocate an deallocated memory
       container2.erase(object->pkid);

}

请咨询

2 个答案:

答案 0 :(得分:4)

如果你的容器持有指针,那么这些对象的析构函数将不会被调用(STL将不会遵循这些指针并调用指针的析构函数)。

相反,如果您的容器本身持有全尺寸对象,则会调用这些对象的析构函数。

您的地图声明和插入语句中也存在一些语法错误。尝试运行以下代码。请注意,析构函数只被称为一次(对于delete语句)。 永远不会为析构语句调用析构函数

#include <map>
#include <string>
#include <iostream>
using namespace std;
//to lazy to write a class 
struct myObj{
    ~myObj() {
        cout << "DESTRUCTION" << endl;
    }
          string pkid;
          string data;
};
map<string,myObj*> container1;
map<string,myObj*> container2;

int main()
{
       myObj * object = new myObj();
       object->pkid="12345";
       object->data="someData";
       container1.insert(pair<string,myObj*>(object->pkid,object));
       container2.insert(pair<string,myObj*>(object->pkid,object));

       //removing POINTER from container1
       container1.erase(object->pkid);
       //object's destructor has NOT been called yet

       //removing POINTER from container2
       container2.erase(object->pkid);
       //object's destructor STILL hasn't been called

       delete object;   // DESTRUCTION!
}

答案 1 :(得分:3)

使用引用计数器确定是否所有容器都删除了您的对象。 Boost有一个参考计数器类shared_ptr

http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm