c++ - enable_shared_from_this 和继承

标签 c++ boost c++11 shared-ptr smart-pointers

我有一个继承自 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/

相关文章:

c++ - 通过转换 boost 状态图传递参数

c++ - g++ 和 boost 中 regex_replace() 替换字符串中 '\' 的不同处理

c++ - 如何在 C++ 中使用默认模板参数显式实例化类?

c++ - 在 C++ 中实现通用构建器模式

c++ - 配置 : error: no boost. 找到文件系统库

c++ - protected 和私有(private)有什么区别?

C++ --- 如何编写正确的代码来释放此示例分配的内存?

c++ - "subset of superset"是什么原理?

c++ - 双参数构造函数的用户定义文字

c++ - 我可以将作用域枚举用于带有模板的 C++ 标记分派(dispatch)吗?