Boost logo

Boost Users :

From: Noah Roberts (roberts.noah_at_[hidden])
Date: 2008-05-16 18:07:13


Kevin Martin wrote:
> On 16 May 2008, at 18:43, Noah Roberts wrote:
>
>> Kevin Martin wrote:
>>> And to make matters worse, people might be tempted to do this!
>>>
>>> func1(func2().get());
>>>
>
>> Having fixed that, your call looks like this:
>>
>> func1(*func2());
>
> My understanding of how this works was wrong. I thought the object
> returned by func2 would go out of scope before the call to func1,
> meaning the pointer/reference passed to func1 would be hanging. It
> seems I am wrong though, at least with g++ and icc, so I guess I need
> to go back to C++ 101.

Actually, I think you are correct on that. A temporary will only
survive into the function call if you are accepting a const& afaik. If
you are accepting a const reference then whatever is passed in will be
bound to that object and is guaranteed to survive. Otherwise no.

Your shared_ptr code actually exhibits a serious issue then. The
shared_ptr is not being bound to anything, only the return of get() is.
  So your shared_ptr will leave scope, be destroyed, and possibly leave
your copy of the pointer returned by get() dangling into a deleted object.

Note that not even accepting "const&" will help you here. The object
pointed to by the shared_ptr is not a temporary and doesn't follow the
rules of such wrt const references. So your shared_ptr could be the
last one, go out of scope, delete the object returned by op*, and then
your function is called with a reference to a deleted object - the worst
of all possible worlds: impossible to defend against and incredibly
difficult to debug.

So you'd better be sure that your shared_ptr is not the last one!
Better to keep a copy during the function call by assigning it to a
local variable and THEN calling your function. Otherwise you are,
effectively, depending on the internals of that function that returned
the shared_ptr.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net