1

If, inside a function, I store data in an unordered_set, and then return pointers to the objects being stored, will the pointers still be valid outside of the scope of the function?

eg.

int *myFunc(){
    std::unordered_set<int> hashset;

    //add some objects
    hashset.insert(4);
    hashset.insert(5);
    hashset.insert(6);

    int *intptr = &(*hashset.insert(4)); //try to insert an object that may already be in the set, and get a pointer to the object in the set
    return intptr;
}

will trying to access *intptr in another function cause an error? Or is the data in an unordered_set deallocated when the scope of an unordered_set ends?

GoogieK
  • 371
  • 2
  • 14
  • http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – chris Jun 06 '14 at 23:23

2 Answers2

3

Yes, in your example you are returning an object which has been destroyed when the destructor of the unordered_set is called, that is when the function exits its scope.

Even though the elements contained in an unordered_set are dynamically allocated (and with elements I mean the objects which contains your effective keys or values) they are also destroyed when the set itself it destroyed.

In practice you could be able to access the data and receive no errors but you shouldn't consider this situation since it's just unsafe. Think only that it is wrong.

To obtain what you need you should take care of inner initialization of objects contained inside the set by yourself. An unique_ptr<int> could do the trick, since returning the value would move it on the destruction of the set and prevent the object from being deallocated.

Jack
  • 131,802
  • 30
  • 241
  • 343
2

The short answer is yes.

The memory inside the hashset object should be considered invalid after the function is called. Thus returning a pointer to the internals of that object will have undefined behavior.

The longer answer is maybe.

However, the state of that memory may remain unchanged for some time after the function has returned. Thus you may get "correct" results from the code despite the memory being invalid.

The longest answer is it depends.

How the memory is handled will depend greatly on the platform that you are running on. Memory constrained systems may perform memory management very differently from desktops.

Andrew Prock
  • 6,900
  • 6
  • 40
  • 60
  • 2
    +1, but just to make it clear to OP: the short answer is the only valid answer, the others are hints at implementation-specific behavior on which you cannot rely. When the container goes out of scope, all its elements are destroyed, period. – Matteo Italia Jun 06 '14 at 23:29