2016-03-21 209 views
0

我正在建造一个工厂类,我需要将unique_ptr返回到BaseClass。返回指针是由使用make_shared被转换到共享指针DerivedClass对象,然后转化为所需BaseClass指针为:dynamic_pointer_cast意外行为

#include "BaseClass.h" 
#include "DerivedClass.h" 

std::unique_ptr<BaseClass> WorkerClass::DoSomething() 
{ 

     DerivedClass derived; 

     // Convert object to shared pointer 
     auto pre = std::make_shared<DerivedClass>(derived); 

     // Convert ptr type to returned type 
     auto ret = std::dynamic_pointer_cast<BaseClass>(ptr); 

     // Return the pointer 
     return std::move(ret); 
} 

I'm获得有关此编译器错误std::move

error C2664: 'std::unique_ptr<_Ty>::unique_ptr(std::nullptr_t) throw()' : cannot convert parameter 1 from 'std::shared_ptr<_Ty>' to 'std::nullptr_t' 
1>   with 
1>   [ 
1>    _Ty=rfidaccess::BaseClass 
1>   ] 
1>   nullptr can only be converted to pointer or handle types 
1>c:\project\dev\traansite1r\traansite1rcommon\tag.cpp(261): error C2664: 'std::unique_ptr<_Ty>::unique_ptr(std::nullptr_t) throw()' : cannot convert parameter 1 from 'std::shared_ptr<_Ty>' to 'std::nullptr_t' 
1>   with 
1>   [ 
1>    _Ty=rfidaccess::BaseClass 
1>   ] 
1>   nullptr can only be converted to pointer or handle types 
1>c:\project\dev\traansite1r\traansite1rcommon\tag.cpp(337): error C2664: 'std::unique_ptr<_Ty>::unique_ptr(std::nullptr_t) throw()' : cannot convert parameter 1 from 'rfidaccess::AARLocomotiveBaseClass' to 'std::nullptr_t' 
1>   with 
1>   [ 
1>    _Ty=rfidaccess::BaseClass 
1>   ] 
1>   nullptr can only be converted to pointer or handle types 
1>c:\project\dev\traansite1r\traansite1rcommon\tag.cpp(393): error C2664: 'std::unique_ptr<_Ty>::unique_ptr(std::nullptr_t) throw()' : cannot convert parameter 1 from 'rfidaccess::AAREndOfTrainBaseClass' to 'std::nullptr_t' 
1>   with 
1>   [ 
1>    _Ty=rfidaccess::BaseClass 
1>   ] 
1>   nullptr can only be converted to pointer or handle types 

我正在使用VS2012 ...

为什么它使用与声明不同的东西(std::unique_ptr<BaseClass>)?

dynamic_pointer_cast没有返回std::unique_ptr<BaseClass> ret?

帮助appreacited找出发生了什么事情。

+1

请注意,这样做'返回的std ::移动();'的自动存储持续时间对象本地的功能是完全多余的。这是隐含的,并且被称为[(Named)返回值优化](https://en.wikipedia.org/wiki/Return_value_optimization) – JBL

回答

4

std::shared_ptr不可转换为unique_ptr

在你的情况,你只想以下:

std::unique_ptr<BaseClass> WorkerClass::DoSomething() 
     return std::make_unique<DerivedClass>(/*args*/); 
} 
+0

当然,我想要一个'unique_ptr',而不是'shared_ptr'!明显 !!谢谢 !!!! – Mendes