Search code examples
c++pointersc++11referenceshared-ptr

Setting std::shared_ptr to point on reference


class a
{
private:
  std::shared_ptr <std::string> sptr;
public:
  void set(std::string & ref)
  {
   sptr = &ref; //error
  }
};

What's the solution? I need to keep the reference as the argument and I need the private pointer to be shared_ptr.


Solution

  • To assign a new raw pointer to a shared pointer and make the shared pointer take ownership, use the member function reset:

    std::shared_ptr<Foo> p;
    
    p.reset(new Foo);
    

    The shared pointer shares ownership of the object, so it's almost impossible to have your sptr share ownership sensibly on an arbitrary reference. (E.g. sptr.reset(&ref) would almost certainly be com­pletely wrong.) The appropriate thing to do is to make a new copy of the string, i.e. either sptr.reset(new std::string(ref)), or better:

    sptr = std::make_shared<std::string>(ref);