STL containers, remove an object from two containers

Suppose I have two containers containing pointers to objects that share some of their elements. from http://www.cplusplus.com/reference/stl/list/erase/ he says that:

This effectively reduces the size of the list by the number of deleted elements, calling each element of the destructor earlier.

How to remove an object from both containers without double calling the destructor:

Example

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

}

consult

+3
source share
2 answers

If there are pointers in your containers, the destructor for these objects will not be called (the STL will not follow these pointers and will call the destination destructor).

, , .

. . , ( 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 destructor has NOT been called yet

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

       delete object;   // DESTRUCTION!
}
+4

Source: https://habr.com/ru/post/1760613/


All Articles