c++ dynamic_pointer_cast意外行为

ldioqlga  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(87)

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

nfg76nw0

nfg76nw01#

std::shared_ptr不能转换为unique_ptr
在您的情况下,您只需要以下内容:

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

相关问题