Search code examples
c++shared-ptr

How to get a reference to an object having shared_ptr to it?


How to get a reference to an object having shared_ptr<T> to it? (for a simple class T)


Solution

  • operator* already returns a reference:

    T& ref = *ptr;
    

    Or, I suppose I could give a more meaningful example:

    void doSomething(std::vector<int>& v)
    {
        v.push_back(3);
    }
    
    auto p = std::make_shared<std::vector<int>>();
    
    //This:
    doSomething(*p);
    
    //Is just as valid as this:
    vector<int> v;
    doSomething(v);
    

    (Note that it is of course invalid to use a reference that references a freed object though. Keeping a reference to an object does not have the same effect as keeping a shared_ptr instance. If the count of the shared_ptr instances falls to 0, the object will be freed regardless of how many references are referencing it.)