Home > Net >  Is this causing a dangling pointer when using map of pointers
Is this causing a dangling pointer when using map of pointers

Time:05-18

This simple code generates a warning about "Object baking the pointer will be destroyed at the end of the full expression". What does that mean? Can I not use the object entry after I use get_map? And also why is this warning showing up

static std::map<std::string, int *> get_map() {
    static std::map<std::string,  int*> the_map;
    return the_map;
}

int main() {
    (...) 
    auto entry = get_map().find("HEY");
    (...)  use entry , is that wrong ?  
}  

CodePudding user response:

Can I not use the object entry after I use get_map?

No, you cannot.

static std::map<std::string, int *> get_map()

returns a copy of the map.

auto entry = get_map().find("HEY");

returns an iterator pointing into the copy. The copy is destroyed immediately after entry is assigned (because the copy was not saved in any variable, it remained a temporary). So, entry can't be safely used.

  • Related