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


Not this code by itself. But you can delete the object and still try to use its reference later



0


source


I strongly disallow this policy, unless you plan on using erase, modification in the future could lead to nasty bugs.

If your object is small enough, return it with a copy.

If the object is rather large, perhaps you can use the boost smart pointer to avoid a segmentation fault.

0


source







All Articles