static_cast 与 boost::shared_ptr?
与 boost::shared_ptr
等效的 static_cast
是什么?
换句话说,
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);
使用 shared_ptr
时我该如何重写以下内容?
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
What is the equivalent of a 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
?
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用boost::static_pointer_cast:
Use
boost::static_pointer_cast
:智能指针共有三个强制转换运算符:
static_pointer_cast
、dynamic_pointer_cast
和const_pointer_cast
。 它们位于命名空间boost
(由
提供)或命名空间std::tr1
(由 Boost 提供)中或通过编译器的 TR1 实现)。There are three cast operators for smart pointers:
static_pointer_cast
,dynamic_pointer_cast
, andconst_pointer_cast
. They are either in namespaceboost
(provided by<boost/shared_ptr.hpp>
) or namespacestd::tr1
(provided either by Boost or by your compiler's TR1 implementation).作为评论:如果 Derived 实际上是从 Base 派生的,那么您应该使用dynamic_pointer_cast 而不是静态强制转换。 系统将有机会检测到您的演员表何时/是否不正确。
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.
值得一提的是,Boost 提供的转换算子数量与 TR1 的实现存在差异。
TR1没有定义第三个运算符const_pointer_cast()
It is worth to mention that the there is difference in the number of casting operators provided by Boost and implementations of TR1.
The TR1 does not define the third operator const_pointer_cast()