Returning a reference to an object belonging to a data structure
My set:
std::set<Object> objects;
I want to find an object and return it as a reference, and also insert it if it doesn't exist:
const Object& get(params...){
Object obj(params...);
std::set<Object>::const_iterator i = objects.find(obj);
if(i != objects.end())
return *i;
objects.insert(obj);
return * objects.find(obj);
}
Could this lead to a segmentation fault, or will it always work?
+3
source to share
3 answers
Depends on what you are doing with the collection.
Insertions and deletions from std::set
will not invalidate iterators for other elements in the collection, but if you are going to remove that element from the collection, then iterators and references to it will be invalidated and you may end up with an invalid reference.
0
source to share