0

我正在建立一个工厂类,我需要将 a 返回unique_ptr到 a 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 吗?

帮助您了解发生了什么。

4

1 回答 1

4

std::shared_ptr不能转换为unique_ptr.

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

std::unique_ptr<BaseClass> WorkerClass::DoSomething()
      return std::make_unique<DerivedClass>(/*args*/);
}
于 2016-03-21T17:21:46.193 回答