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 useget_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.