philips_dvd
philips_dvd

Reputation: 83

What's the proper way to save a reference to an object with shared_ptr

What's the difference between using std::shared_ptr with & and without in order to save a reference to an object?

class A{};

class B
{
private:
    std::shared_ptr<A>&obj; // or std::shared_ptr<A>obj;
public:
    B(std::shared_ptr<A>r) : obj(r) {}
};

int main()
{
    std::shared_ptr<A>a(new A());
    std::unique_ptr<B>b(new B(a));
    std::cin.get();
    return 0;
}

Upvotes: 1

Views: 1189

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

Making B::obj a reference is the same no matter what type it is. A reference is a reference is a reference, doesn't matter if it's a reference to an int or to a std::shared_ptr<A>.

And note that since you pass the B constructor argument by value, it will go out of scope once the constructor returns, leaving any reference to r invalid.

Lastly, it really doesn't make any sense to save a reference to a std::shared_ptr. It sometimes makes sense to pass a std::shared_ptr reference argument, but not really storing such a reference. The reference is to the std::shared_ptr object, not what the std::shared_ptr is pointing to, using a reference will not increase the internal counter, and will not use the shared ownership semantics of std::shared_ptr.

In other words: Don't save references to std::shared_ptr.

Upvotes: 5

Related Questions