dynamic_pointer_cast意外行为

时间:2016-03-21 17:15:36

标签: c++ c++11 unique-ptr make-shared

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

帮助appreacited了解发生了什么。

1 个答案:

答案 0 :(得分:4)

std::shared_ptr无法转换为unique_ptr

在您的情况下,您只需要以下内容:

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