Boost logo

Boost :

Subject: Re: [boost] [smart_ptr] Moving cast for unique_ptr
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-10-07 03:03:29


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).

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).

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.

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.


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