我有一个继承自 enable_shared_from_this<type>
的类型,以及从该类型继承的另一种类型。现在我不能使用 shared_from_this 方法,因为它返回基类型,并且在特定的派生类方法中我需要派生类型。直接从这里构造一个 shared_ptr 是否有效?
编辑:
在一个相关问题中,我如何才能从 shared_ptr<base>
类型的右值移动类型为 shared_ptr<derived>
?我使用 dynamic_cast 来验证它确实是正确的类型,但现在我似乎无法完成实际的移动。
最佳答案
一旦您获得 shared_ptr<Base>
, 你可以使用 static_pointer_cast
将其转换为 shared_ptr<Derived>
.
您不能只创建 shared_ptr
直接来自 this
;这相当于:
shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts
关于c++ - enable_shared_from_this 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491420/