Suppose we have the following classes:
struct A
{
virtual ~A() = default;
};
struct B : A
{ };
In addition, we have a factory function that returns generic smart pointers of type A:
std::shared_ptr<A> FuncionFactoria(int n)
{
if( n % 2 )
return std::make_shared<A>();
else
return std::make_shared<B>();
}
And on the other hand, we have a couple of functions. One supports a smart pointer of type A and the other a smart pointer of type B:
void FuncionGenerica(std::shared_ptr<A>);
void FuncionEspecifica(std::shared_ptr<B>);
How could one perform a safe conversion between pointers? A possible example of use:
int main()
{
for( int i=0; i<10; i++ )
{
std::shared_ptr<A> aSptr = FuncionFactoria(i);
std::shared_ptr<B> bSptr = /* ¿¿¿??? */
if( bSptr )
FuncionEspecifica(bSptr);
FuncionGenerica(aSptr);
}
}
Note that pointers of type A must be valid after conversion...
The smart pointer transformation tools provided by the standard library should suffice :
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r );
the equivalent tostatic_cast
with other data types.std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r );
the equivalent todynamic_cast
with other data types.std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r );
the equivalent toconst_cast
with other data types.std::shared_ptr<T> reinterpret_pointer_cast( const std::shared_ptr<U>& r );
the equivalent toreinterpret_cast
with other data types.All of these conversions are available through the header
<memory>
which, if you're using smart pointers, you'll need to have included at some point.If we look at implementation 1 of smart pointer conversion, we can see that
std::static_pointer_cast
it behaves like this:According to the documentation available in cppreference it is using the eighth constructor whose details are:
So, in your case it can be used
std::static_pointer_cast
in your code without affecting its security:1 The exact implementation will vary between compilers, but the C++ standard guarantees that behavior will be the same regardless of implementation details.