I have a class hierarchy as follows:
class BaseSession : public boost::enable_shared_from_this
class DerivedSessionA : public BaseSession
The question has been clarified:
sorry I was not clear. I want the ownership to remain with original owner, the called function should only get reference to it, not ownership. Not looking for two smart pointer for the same object.
In that case, the solution is simply:
dynamic_cast(*my_unique_ptr)
Done. It throws if the cast doesn't succeed.
shared_ptr
For shared_ptr
there is std::dynamic_pointer_cast<>
(http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast)
unique_ptr
The simplest way would seem:
#include
struct A { virtual ~A() = default; };
struct B : A { };
int main()
{
std::unique_ptr pa(new B);
std::unique_ptr pb(dynamic_cast(pa.release())); // DO NOT DO THIS
}
As the commenter rightfully points out, this may leak the object if the conversion failed. That's not very helpful.
A reason why the dynamic_unique_ptr_cast<>
doesn't exist might be that the unique_ptr
type doesn't erase the deleter. It could be hard/impossible to choose an appropriate delete for the target pointer type.
However, for simple cases, you could use something like this:
template
std::unique_ptr dynamic_unique_cast(std::unique_ptr&& p) {
if (To* cast = dynamic_cast(p.get()))
{
std::unique_ptr result(cast, std::move(p.get_deleter()));
p.release();
return result;
}
return std::unique_ptr(nullptr); // or throw std::bad_cast() if you prefer
}
auto pb = dynamic_unique_cast(std::move(pa));