I understand that using static_pointer_cast with unique_ptr would lead to a shared ownership of the contained data.
Only if you define it badly. The obvious solution would be for it to transfer ownership, so that the source object ends up empty.
If you don't want to transfer ownership then just use a raw pointer.
Or if you want two owners then use shared_ptr
.
It seems like your question is only partly about the actual cast operation, and partly just lack of a clear ownership policy for the pointer. If you need multiple owners, whether they both use the same type, or whether one is cast to a different type, then you should not be using unique_ptr
.
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.
No, that's not why it doesn't exist. It doesn't exist because it's trivial to write it yourself, if you need it (and as long as you give it sane semantics of unique ownership). Just get the pointer out with release()
cast it, and put it in another unique_ptr
. Simple and safe.
That isn't the case for the shared_ptr
, where the "obvious" solution doesn't do the right thing:
shared_ptr<Derived> p2(static_cast<Derived*>(p1.get());
That would create two different shared_ptr
objects that own the same pointer, but don't share ownership (i.e. they would both try to delete it, causing undefined behaviour).
When shared_ptr
was first standardized there was no safe way to do that, so static_pointer_cast
and the related casting functions were defined. They needed access to the implementation details of the shared_ptr
bookkeeping info to work.
However, during the C++11 standardization process shared_ptr
was enhanced by the addition of the "aliasing constructor" which allows you to do the cast simply and safely:
shared_ptr<Derived> p2(p1, static_cast<Derived*>(p1.get());
If this feature had always been part of shared_ptr
then it's possibly, maybe even likely, that static_pointer_cast
would never have been defined.
static_pointer_cast
is only defined for argument of typestd::shared_ptr<T>
- it is not usable at all withunique_ptr
unique_ptr
.struct B { virtual void f() = 0; }; template<class T> struct D: public B { void f() override { /* do something with D */ } };
, have you ever done something like that? With the good mix of wrappers andstatic_pointer_cast
you can create a lot of interesting things.