c++ - Is it wise to use a pointer to access values in an std::map -
is dangerous returning pointer out of std::map::find
data , using opposed getting copy of data?
currently, pointer entry in map , pass function display data. i'm concerned items moving causing pointer become invalid. legit concern?
here sample function:
mystruct* structmanagementclass::getstructptr(int structid) { std::map<int, mystruct>::iterator foundstruct; foundstruct= mystructlist.find(structid); if (foundstruct== mystructlist.end()) { mystruct newstruct; memset(&newstruct, 0, sizeof(mystruct)); mystructlist.structid= structid; mystructlist.insert(pair<int, mystruct>(structid, newstruct)); foundstruct= mystructlist.find(structid); } return (mystruct*) &foundstruct->second;
}
it undoubtedly more typical return iterator pointer, though makes little difference.
as far remaining valid goes: map iterator remains valid until/unless item refers removed/erased map.
when insert or delete other node in map, can result in nodes in map being rearranged. that's done manipulating pointers between nodes though, changes other nodes contain pointers node care about, not change address or content of particular node, pointers/iterators node remain valid.
Comments
Post a Comment