C++ 带有 boost::shared_ptr 的 static_cast?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/624854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
static_cast with boost::shared_ptr?
提问by Frank
What is the equivalent of a static_cast
with boost::shared_ptr
?
static_cast
与 with的等价物是boost::shared_ptr
什么?
In other words, how do I have to rewrite the following
换句话说,我该如何重写以下内容
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);
when using shared_ptr
?
什么时候使用shared_ptr
?
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
回答by Frank
Use boost::static_pointer_cast
:
使用boost::static_pointer_cast
:
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);
回答by Michael Kristofik
There are three cast operators for smart pointers: static_pointer_cast
, dynamic_pointer_cast
, and const_pointer_cast
. They are either in namespace boost
(provided by <boost/shared_ptr.hpp>
) or namespace std::tr1
(provided either by Boost or by your compiler's TR1 implementation).
有三种类型转换操作符的智能指针:static_pointer_cast
,dynamic_pointer_cast
,和const_pointer_cast
。它们位于命名空间boost
(由 提供<boost/shared_ptr.hpp>
)或命名空间std::tr1
(由 Boost 或编译器的 TR1 实现提供)。
回答by David Rodríguez - dribeas
As a comment: if Derived does in fact derive from Base, then you should use a dynamic_pointer_cast rather than static casts. The system will have a chance of detecting when/if your cast is not correct.
作为评论:如果 Derived 实际上是从 Base 派生的,那么您应该使用 dynamic_pointer_cast 而不是静态强制转换。系统将有机会检测您的演员何时/是否不正确。
回答by mloskot
It is worth to mention that the there is difference in the number of casting operators provided by Boost and implementations of TR1.
值得一提的是,Boost 提供的转换运算符的数量与 TR1 的实现存在差异。
The TR1 does not define the third operator const_pointer_cast()
TR1 没有定义第三个操作符 const_pointer_cast()