加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:29:23 所属栏目:百科 来源:网络整理
导读:假设我有两个容器,它们持有指向对象的指针,这些指针共享一些元素. 从 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.
假设我有两个容器,它们持有指向对象的指针,这些指针共享一些元素.

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声明和insert语句中也有一些语法错误.尝试运行以下代码.请注意,析构函数只被调用一次(对于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,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!
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读