Alternatives of static_pointer_cast for unique_ptr

Viewed 41113

I understand that using static_pointer_cast with unique_ptr would lead to a shared ownership of the contained data.
In other terms, what I'd like to do is:

unique_ptr<Base> foo = fooFactory();
// do something for a while
unique_ptr<Derived> bar = static_unique_pointer_cast<Derived>(foo);

Anyway doing that results with two unique_ptr that should never exist at the same time, so it is simply forbidden.
Right, it makes sense, absolutely, that's why there doesn't exist anything like static_unique_pointer_cast indeed.

So far, in cases where I want to store pointers to those base classes, but I also need to cast them to some derived classes (as an example, imagine a scenario involving type erasure), I've used shared_ptrs because of what I've above mentioned.

Anyway, I was guessing if there are alternatives to shared_ptrs for such a problem or if they are really the best solution in that case.

3 Answers
Related