Search code examples
c++c++11boostshared-ptr

Return a dereferenced value of shared_ptr from a function


Here is a rookie question. Is the following code safe?

boost::unordered_set<std::string> func()
{
      boost::shared_ptr<boost::unordered_set<std::string>> list =
              boost::make_shared<boost::unordered_set<std::string>>();

      /* Code to populate the shared_ptr to unordered_set goes here and I do
         populate my set. */

      return *list;
}

What will happen first? Copying/NRVO/moving or destruction of shared_ptr there by causing memory fault? If unsafe, what are my alternatives?


Solution

  • This happens:

    • A temporary copy of the pointed object is made. This is the return value of the function. The copy can not be elided.
    • The local variables of the function, including the shared pointer are destroyed.
    • When the shared pointer is destroyed, the refcount is decremented. If no copies of the shared pointer were made within the function, refocount will reach 0 and the pointed object is destroyed.

    It is safe, but the use of dynamic allocation, and shared pointer seems pointless and the inefficiency of the copy may hurt performance if the set is large.


    Since you haven't demonstrated any need for using the pointer, I suggest a simpler alternative:

    boost::unordered_set<std::string> list;
    
    /* Code to populate the unordered_set goes here and I do
         populate my set. */
    
    return list;
    

    NRVO can be applied to this and if it's not applied, the return value is constructed by move.