ewerton
ewerton

Reputation: 447

Returning a reference to an object owned by a data structure

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?

Upvotes: 3

Views: 108

Answers (3)

Nicola Pezzotti
Nicola Pezzotti

Reputation: 2367

I strongly discourage this policy also if you don't plan to use erase, a modification in future could lead to nasty bugs.

If your object is small enough return it by copy.

If the object is quite big maybe you can use a boost smart pointer to avoid segmentation fault.

Upvotes: 0

TeaOverflow
TeaOverflow

Reputation: 2578

Not this code by itself. But you might erase an object and still attempt to use its reference later

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126442

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.

Upvotes: 1

Related Questions