Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从\u和继承中启用\u共享\u_C++_Boost_C++11_Shared Ptr_Smart Pointers - Fatal编程技术网

C++ 从\u和继承中启用\u共享\u

C++ 从\u和继承中启用\u共享\u,c++,boost,c++11,shared-ptr,smart-pointers,C++,Boost,C++11,Shared Ptr,Smart Pointers,我有一个类型继承自enable\u shared\u from\u this,另一个类型继承自此类型。现在我不能使用这个方法中的shared_from_,因为它返回基类型,而在特定的派生类方法中,我需要派生类型。直接从中构造一个共享的_ptr有效吗 编辑: 在一个相关的问题中,如何将类型为shared\u ptr的右值转换为类型为shared\u ptr?我使用dynamic_-cast来验证它是否真的是正确的类型,但现在我似乎无法完成实际的移动。一旦您获得共享的\u-ptr,您可以使用将其转换

我有一个类型继承自
enable\u shared\u from\u this
,另一个类型继承自此类型。现在我不能使用这个方法中的shared_from_,因为它返回基类型,而在特定的派生类方法中,我需要派生类型。直接从中构造一个共享的_ptr有效吗

编辑:
在一个相关的问题中,如何将类型为
shared\u ptr
的右值转换为类型为
shared\u ptr
?我使用dynamic_-cast来验证它是否真的是正确的类型,但现在我似乎无法完成实际的移动。

一旦您获得
共享的\u-ptr
,您可以使用将其转换为
共享的\u-ptr

你不能直接从这个
创建一个
共享的\u ptr
;这相当于:

shared_ptr<T> x(new T());
shared_ptr<T> y(x.get()); // now you have two separate reference counts
shared_ptr x(新的T());
共享_ptr y(x.get());//现在有两个独立的引用计数

No,您不能使用
static\u pointer\u cast
shared\u ptr
向下转换为
shared\u ptr
。必须使用
dynamic\u pointer\u cast
,因为可能有任意数量的派生类。@Myon为什么不呢?你是什么意思?@curiousguy:如果你使用的是非虚拟继承,并且你100%确定要强制转换的类型,那么你可以使用
静态\u指针\u强制转换
。任何其他情况都是未定义的行为。因此,在一般情况下使用
动态指针\u cast
时,您将处于安全的一方-这就是我的建议。