【问题标题】:unique_ptr upcast in returnunique_ptr 向上转换作为回报
【发布时间】:2013-08-19 17:47:12
【问题描述】:

我有这个函数应该生成不同的派生对象并以unique_ptr<base> 的形式返回:

class base {};  // contains pure functions.
class derived1 {}; // reifies that pure iface.
class derived2 {}; // reifies that pure iface.

unique_ptr<base> factory::load(int param)
  {
    switch (param)
      {
      case PARAM_MAIN:
        return new derived1();
        // return std::move(new derived1());

      case PARAM_2:
        return new derived2();

      case ...:
        return new derived...();

      }
  }

即使使用 std::move,我也无法完成这件事。 (也使用了dynamic_cast,但可能做错了)。

这是我得到的错误:(ArchLinux 上的 gcc (GCC) 4.8.1 20130725 (prerelease))

could not convert '(std::shared_ptr<base::model>((*(const std::shared_ptr<base::model>*)(& associatedModel))), (operator new(48ul), (<statement>, ((derived1*)<anonymous>))))' from 'derived1*' to 'std::unique_ptr<base>'
            associatedModel));

我希望我已经清楚自己想要做什么。

我该怎么做?谢谢。

【问题讨论】:

  • "这是我得到的错误" 不知何故,我认为代码不会给出该错误。特别是因为它提到了shared_ptr,您没有使用它。您的代码中似乎有一些您没有向我们展示的内容。
  • derived1 和 derived2 是否应该从 base 继承?因为现在您正试图在正交类型之间进行隐式转换,这通常是不允许的(也不是一个好主意)。

标签: c++11 polymorphism unique-ptr upcasting


【解决方案1】:

您可以使用unique_ptr&lt;derived1&gt;(new derived1());,甚至更好(使用C++14)使用std::make_unique。

using namespace std;

class base {};  // contains pure functions.
class derived1 {}; // reifies that pure iface.
class derived2 {}; // reifies that pure iface.

unique_ptr<base> factory::load(int param) {
  switch (param) {
    case PARAM_MAIN: return make_unique<derived1>();
    case PARAM_2:    return make_unique<derived2>();
    case ...:        return make_unique<derived...>();
  }
}

【讨论】:

    【解决方案2】:

    我是这样解决的:

    return unique_ptr<base>(dynamic_cast<base*>(std::move(
                   new derived1()
           )));
    

    所以关键是它必须在它仍然是原始的时候被向上转换为base,然后才被包裹在unique_ptr中。

    无论如何,我很欣赏更简单的答案。尤其是那些基于 unique_ptr 内部和实现的推理。

    【讨论】:

    • std::unique_ptr的构造函数是explicit,所以return new blah();不起作用。 return unique_ptr&lt;Derived1&gt;(new derived1()); 工作正常。
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多