相对于static_cast,即。所以,如果我们有这两个类型转换
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)
第 (2) 行会比第 (1) 行慢吗?
最佳答案
是的,它有更多的开销,因为它必须返回一个新的 shared_ptr 而不是一个新的原始指针。
boost 实现是:
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 );
}
因此,返回行创建了一个 shared_ptr,它拥有与您正在转换的 shared_ptr 完全相同的原始指针。查看此构造函数,它会导致同时分配被管理的指针和指向控制 block 的指针——这是额外的开销。它基本上是两个指针赋值,而不是一个。
编辑 2:还会有一个原子引用计数增量,其性能影响将超过正常增量。
编辑:适用于性能问题的常见警告。实现可能会有所不同。这不是标准规定的开销。始终衡量绩效!
关于c++ - std::static_pointer_cast 是否有任何额外的运行时开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447562/