简体   繁体   English

C ++删除地图中的指针

[英]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? 为什么这段代码没有设置指向nullptr的指针? Am I setting a local variable to nullptr? 我是否将局部变量设置为nullptr?

You should use a reference to an element of the value type in the loop instead of using a copy. 您应该在循环中使用对值类型的元素的引用,而不是使用副本。 For example 例如

for ( pair<const string,Plaats*> &place : plaatsen){
    //Plaats *p = place.second;
    delete place.second;
    place.second = nullptr;
}

Also take into account that the key shall have qualifier const pair<const string,Plaats*> . 还要考虑到键应该有限定符const pair<const string,Plaats*>

You need to use a reference to avoid copying. 您需要使用引用来避免复制。

for(pair<string,Plaats*>& place : plaatsen){

Edit: I missed a const in the above answer. 编辑:我在上面的答案中错过了一个const So Vlad's answer is better. 弗拉德的答案更好。 Robinson's comment on my answer makes an even better answer. 罗宾逊对我的回答的评论做出了更好的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM