enable_shared_from_this和继承

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)

  • @curiousguy:如果您使用非虚拟继承并且您 100% 确定要转换为的类型,则可以使用 `static_pointer_cast`。任何其他情况都是未定义的行为。因此,一般情况下使用“dynamic_pointer_cast”,你就会处于安全的状态 - 这就是我所说的。 (2认同)