Pup*_*ppy 27 c++ boost smart-pointers shared-ptr c++11
我有一个继承自的类型enable_shared_from_this<type>,以及从这种类型继承的另一种类型.现在我不能使用shared_from_this方法,因为它返回基类型,并且在特定的派生类方法中我需要派生类型.从这个直接构造shared_ptr是否有效?
编辑:在一个相关的问题中,我如何从一个类型的左值移动shared_ptr<base>到一个类型shared_ptr<derived>?我使用dynamic_cast来验证它确实是正确的类型,但现在我似乎无法完成实际的移动.
Jam*_*lis 21
获得后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
Run Code Online (Sandbox Code Playgroud)