与 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)慢吗?
与 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)
是的,使用shared_ptr会增加一些开销,因为它需要返回一个新的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 );
}
(void) static_cast< T* >( static_cast< U* >( 0 ) );
在 Boost 实现中的目的是什么(我猜它与类型检查有关,但不确定具体细节)? - Hongxu Chenshared_ptr
会保存所需的信息以及一个删除器函数,以用于关联对象的销毁。共同控制块也会保存在其中,这个块会被相同引用对象的 shared_ptr
实例共享。而 static_pointer_cast
只是简单地将一个指向 shared_ptr
实例的指针进行类型转换,因此,尽管它可以更改指针值,但不应该涉及任何额外开销(除了像复制一个实例一样创建 shared_ptr
实例)。
据我所知,目前没有正式的保证(如果这对您很重要,请查阅相关信息)。
static_cast<Derived*>(b.get())
的语法糖。 - Rapptzstatic_pointer_cast
可以用于shared_ptr
智能指针对象。 - Cheers and hth. - Alf