Is it safe to dereference a newly created shared_ptr function call?

Let A be a class.

Consider the following snippet:

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

Now this clearly does not work, because the reference count in shared_ptr of instance A in the first line is reduced to zero, and the instance is destroyed. If I compile this in VS2010, I get runtime errors. It's great. Instead, I could do this:

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

which is safe and legal.

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

CallSomeFunctionAcceptingAReferenceToA(*make_shared<A>());

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

+4
source share

All Articles