Does std::static_pointer_cast have any additional runtime overhead?

c++

Solution

Yes, it has more overhead, because it has to return a new shared_ptr as opposed to a new raw pointer.

The boost implementation is:

template<class T, class U> shared_ptr<T> static_pointer_cast( shared_ptr<U> const & r ) BOOST_NOEXCEPT
{
    (void) static_cast< T* >( static_cast< U* >( 0 ) );

    typedef typename shared_ptr<T>::element_type E;

    E * p = static_cast< E* >( r.get() );
    return shared_ptr<T>( r, p );
}

So the return line creates a shared_ptr which owns the very same raw pointer as the shared_ptr you are casting. Looking at this constructor, it will cause an assignment of both the pointer being managed and a pointer to the control block - this is the extra overhead. It's basically two pointer assignments instead of one.

Edit 2: There will also be an atomic reference count increment, the performance impact of which will be more than a normal increment.

Edit: Usual caveats where performance issues apply. Implementations can vary. This is not a standard-mandated overhead. And always always measure performance!

Problem

Compared to static_cast, that is. So, if we have these two casts ``` Base* b(new Derived()); Derived* d = static_cast<Derived*>(b); // (1) shared_ptr<Base> b(new Derived()); shared_ptr<Derived> d = static_pointer_cast<Derived>(b); // (2) ``` will line (2) be slower than line (1)?

Original source