STL容器,从两个容器中移除对象。

3
假设我有两个容器,它们持有指向对象的指针,并且共享一些元素。从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);

}

请给予建议。

4
实际上,对象的析构函数并没有被调用;erase 只是从 map 中删除指针。如果 map 中包含的是对象而不是指针,则会调用它们的析构函数。 - Mike Seymour
2个回答

4
如果容器中保存指针,那么这些对象的析构函数将不会被调用(STL不会跟随这些指针并调用被指向对象的析构函数)。
相反,如果容器中保存的是完整的对象本身,则这些对象的析构函数将被调用。
另外,在您的map声明和插入语句中还存在一些语法错误。请尝试运行以下代码。请注意,析构函数仅被调用一次(用于删除语句)。从未为删除语句调用析构函数。
#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
我明白了。所以在指针的情况下,我需要在从所有容器中取出它们后显式地删除它们。 谢谢! - Alex

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接