我正在建造一個工廠類,我需要將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找出發生了什麼事情。
請注意,這樣做'返回的std ::移動();'的自動存儲持續時間對象本地的功能是完全多餘的。這是隱含的,並且被稱爲[(Named)返回值優化](https://en.wikipedia.org/wiki/Return_value_optimization) – JBL