user1873947
user1873947

Reputation: 1811

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.

Upvotes: 2

Views: 2213

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476990

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);

Upvotes: 7

ForEveR
ForEveR

Reputation: 55887

If you want to store address of your reference then you can use

sptr = std::shared_ptr<std::string>(&ref, [](const std::string*){});

Else if you want to store new object - use Kerrek SB variant.

Upvotes: 2

Related Questions