Boost logo

Boost :

Subject: Re: [boost] [smart_ptr] Moving cast for unique_ptr
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2015-10-07 14:06:27


Le 07/10/15 09:03, Gavin Lambert a écrit :
> On 7/10/2015 19:16, Vicente J. Botet Escriba wrote:
>> Just wondering if we can not make dynamic_pointer_cast to work as your
>> dynamic_moving_pointer_cast, when the parameter is a rvalue reference
>>
>> template<class T, class U>
>> shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> && r) noexcept;
>>
>> C++ International Standard
>> The use will be
>>
>> dynamic_pointer_cast<U>(ret_up());
>> dynamic_pointer_cast<U>(move(up));
>
> It would theoretically be possible if you have access to the internals
> of shared_ptr (otherwise it would be no better than copying).
Well we have boost::unique_ptr to play with.
>
> However I'm dubious about this usage -- dynamic casts naturally admit
> the possibility of failure, which results in discarding the input
> parameter in cases that it's a temporary (hence the changed semantics
> in the proposed dynamic_moving_pointer_cast).
IIUC passing the unique_ptr by reference allows to don't move if the
dynamic_cast fails. I don't see how this implies an exception.
>
> This basically translates into an operation that says "return the
> pointer without touching its refcount if the cast succeeds, otherwise
> decrement the refcount". In particular the latter case can result in
> almost immediately deleting a value newly-created by the called
> function, or otherwise unique prior to the cast.
Good point.
>
> The equivalent operation on unique_ptr would simply be "delete input
> pointer if cast fails".
>
> Either of these seem like an odd thing for code to want to do in
> practice. Usually polymorphic code doesn't transfer ownership at the
> same time. I'm curious if there would be any good real-world examples
> for this.
>
I agree with your analysis.

Vicente


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk