Le 06/10/15 12:19, Karolin Varner a écrit :
Hi all!
There is the family of boost pointer cast (boost::static_pointer_cast, boost::dynamic_pointer_cast, ...) that allow a developer to write generic code by casting pointers regardless of whether they are some smart pointer (e.g. shared_ptr) or plain pointers.
However, those functions have not been implemented for unique_ptr, because they create a copy of their pointer and unique_pointers can not be copied.
In my case I still needed to cast some unique_ptr and since it's ok to move unique_ptrs I wrote a function that does exactly that. The code is below – Comments are very, very welcome. It works for my case, but I am sure it is not as generic and safe as it should be ;) . Specifically, for a library, it should be made to work on any kind of smart/plain pointer. Not just unique_ptr.
Is there any interest to include a boost::static_moving_pointer_cast and the other types of casts in boost? I believe this will be a useful addition.
/// Dynamic cast a unique_ptr. /// /// This function shall move the pointer in in_ptr, into /// a new unique_pointer of the desire type, dynamic_casting /// it in the process. /// In given pointer shall contain a NULL pointer afterwards. /// /// If unsuccessful, function shall throw an error and leave /// in_ptr unmodified. /// /// This behaviour contrasts a bit with the behaviour of the /// normal dynamic_cast: /// 1. dynamic_cast copies objects, this moves them since /// unique_pointers can not be copied. /// 2. dynamic_cast returns a NULL pointer if the pointer to /// cast is of an incomplete type, this throws /// incomplete_cast instead, to ease error handling. I wouldn't throw in this case to be coherent with dynamic_pointer_cast. If you need a better error handling for dynamic_moving_pointer_cast you need also for dynamic_pointer_cast.
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