我正在建造一个工厂类,我需要将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