3

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
ewerton
  • 427
  • 1
  • 6
  • 13

3 Answers3

1

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.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • Probably yes (and if you will use pointers, consider using *smart* pointers), but it's hard to say without knowing the logics of your application. I guess it all depends on whether you need reference semantics or not. Maybe [this Q&A](http://stackoverflow.com/questions/14539624/memory-management-patterns-in-c/14539873#14539873) will help delucidating – Andy Prowl Feb 04 '13 at 18:21
  • Actually smart pointers would not be appropriate really, since there would be no ownership going on with the pointer being returned. Unless you want to make the whole container contain `shared_ptr` or something. – Seth Carnegie Feb 04 '13 at 18:23
  • @SethCarnegie: That's what I meant. The container would be a `set>`. – Andy Prowl Feb 04 '13 at 18:26
0

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

TeaOverflow
  • 2,468
  • 3
  • 28
  • 40
0

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.

Nicola Pezzotti
  • 2,317
  • 1
  • 16
  • 26