dimanche 1 novembre 2015

C++ deleting pointers in a map

Deleting heap items with a pointer in a map

I have this map:

map<string, Plaats*> plaatsen;

In a function I am adding places to this map like this:

Plaats * fromPlace = new Plaats(from);
Plaats * toPlace = new Plaats(to);
auto insertedFrom = plaatsen.insert(pair<string,Plaats*>(from,fromPlace));
auto insertedTo = plaatsen.insert(pair<string,Plaats*>(to,toPlace));
//delete from or to if they are not inserted
if(!insertedFrom.second){
    delete fromPlace;
}
if(!insertedTo.second){
    delete toPlace;
}

If the element is added to my map, I need to delete it in my destructor.

KortstePad::~KortstePad(){
    //delete every item in plaatsen
    for(pair<string,Plaats*> place : plaatsen){
        //Plaats *p = place.second;
        delete place.second;
        place.second = nullptr;
    }

    for(pair<string,Plaats*> place : plaatsen){
        Plaats *p = place.second;
        cout << (p == nullptr) << endl;
    }
}

It appears my code is not deleting my places, because this is the output of the program:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

Why is this code not setting my pointers to nullptr? Am I setting a local variable to nullptr?

Aucun commentaire:

Enregistrer un commentaire