2016-03-21 213 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