enable_shared_from_this和继承 [英] enable_shared_from_this and inheritance
问题描述
我已经得到了从 enable_shared_from_this&LT继承的类型;类型>
,和另一种类型的,从这个类型继承。现在,因为它返回的基本类型和具体的派生类的方法,我需要派生类型,我不能用shared_from_this方法。它是有效的,只是从这个构造一个shared_ptr直接?
I've got a type which inherits from enable_shared_from_this<type>
, and another type that inherits from this type. Now I can't use the shared_from_this method because it returns the base type and in a specific derived class method I need the derived type. Is it valid to just construct a shared_ptr from this directly?
编辑:
在一个相关的问题,我怎么能在类型的右值移动的shared_ptr&LT;基地&GT;
来一个类型的的shared_ptr&LT;衍生&GT;
?我用的dynamic_cast以验证它确实是正确的类型,但现在我似乎无法完成的实际行动。
In a related question, how can I move from an rvalue of type shared_ptr<base>
to a type of shared_ptr<derived>
? I used dynamic_cast to verify that it really was the correct type, but now I can't seem to accomplish the actual move.
推荐答案
一旦你获得的shared_ptr&LT;基地以及GT;
,你可以使用<一个href=\"http://www.boost.org/doc/libs/1_45_0/libs/smart_ptr/shared_ptr.htm#static_pointer_cast\"><$c$c>static_pointer_cast$c$c>将其转换为一个的shared_ptr&LT;衍生方式&gt;
Once you obtain the shared_ptr<Base>
, you can use static_pointer_cast
to convert it to a shared_ptr<Derived>
.
您不能只是创建一个的shared_ptr
直接这个
;这将是等同于:
You can't just create a shared_ptr
directly from this
; that would be equivalent to:
shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts
这篇关于enable_shared_from_this和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!