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

标签 c++ stl map containers

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

This effectively reduces the list size by the number of elements removed, calling each element's destructor before.

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

例子

#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);

}

请多多指教

最佳答案

如果您的容器持有指针,则不会调用这些对象的析构函数(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!
}

关于c++ - STL 容器,从两个容器中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524915/

相关文章:

c++ - vector 、Size_type 和封装

android - AndEngine在多个设备上加载TMX map

c++ - 使用来自 const 成员函数的每个类 boost::log::sources::logger

c++ - 消除未使用的虚函数

c++ - 如何聚合从虚拟类型继承的结构的初始化?

java - Freemarker:如何使用枚举作为键来遍历 map

javascript - 什么是商业应用程序的好 map api?

c++ - Valgrind 提示使用依赖于未初始化字节的条件跳转

c++ - 如何在自定义类中启用 'auto loops'?

c++ - 2种不同的种类,1个仿函数