我正在构建一个工厂类,我需要将unique_ptr
返回到BaseClass
。返回的指针由一个DerivedClass
对象组成,该对象使用make_shared
转换为共享指针,然后转换为所需的BaseClass
指针:
#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);
}
我在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吗?
1条答案
按热度按时间nfg76nw01#
std::shared_ptr
不能转换为unique_ptr
。在您的情况下,您只需要以下内容: