My set:
std::set<Object> objects;
I want find a object and return it as a reference, also inserting 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);
}
This can result in a segmentation fault or this will work always?
Depends what you do with the collection.
Insertions and removals from an std::set won't invalidate iterators to the other elements of the collection, but if you are going to erase that element from the collection, then the iterators and references to it will be invalidated and you might end up with an invalid reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With