What is shared_ptr’s aliasing constructor for?

Simple example:

struct Bar { 
    // some data that we want to point to
};

struct Foo {
    Bar bar;
};

shared_ptr<Foo> f = make_shared<Foo>(some, args, here);
shared_ptr<Bar> specific_data(f, &f->bar);

// ref count of the object pointed to by f is 2
f.reset();

// the Foo still exists (ref cnt == 1)
// so our Bar pointer is still valid, and we can use it for stuff
some_func_that_takes_bar(specific_data);

Aliasing is for when we really want to point to Bar, but we also don’t want the Foo to get deleted out from under us.


As Johannes points out in the comments, there is a somewhat equivalent language feature:

Bar const& specific_data = Foo(...).bar;
Bar&& also_specific_data = Foo(...).bar;

We’re taking a reference to a member of a temporary, but the temporary Foo is still kept alive as long as specific_data is. As with the shared_ptr example, what we have is a Bar whose lifetime is tied to a Foo – a Foo that we cannot access.

Leave a Comment