Search code examples
c++unordered-set

Is the data in an std::unordered_set erased when a function ends?


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?


Solution

  • 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.