Is it safe to dereference a just-created shared_ptr in function call?

131 views Asked by At

Let A be a class.

Consider the following snippet:

A& a = *make_shared<A>();
CallSomeFunctionAcceptingAReferenceToA(a);

Now, this clearly doesn't work, because the reference counter in the shared_ptr to the instance of A is decremented to zero in the first line, and the instance is destructed. If I compile this in VS2010 I get runtime errors. That's fine. Instead, I could do this:

auto a = make_shared<A>();
CallSomeFunctionAcceptingAReferenceToA(*a);

which is safe and legal.

I want to write this more compactly, so what about this:

CallSomeFunctionAcceptingAReferenceToA(*make_shared<A>());

(note in my application the make_shared is replaced by a call to a factory which returns shared_ptr to an instance). If I compile this in VS2010, the program runs fine, but is it legal according to the C++ standard?

0

There are 0 answers