【问题标题】:Override method with shared_ptr Base type with shared_ptr Derived type使用 shared_ptr 覆盖方法 使用 shared_ptr 派生类型的基本类型
【发布时间】:2021-06-15 23:06:57
【问题描述】:

我正在尝试创建一个抽象方法来克隆从 base 派生的类并将它们作为 shared_ptr 返回,如下所示:

class Base {
public:
    virtual std::shared_ptr<BaseSymbol> clone() = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);
    std::shared_ptr<Derived> clone();
};

这让我遇到编译错误。我知道这可以用普通指针来实现,那么我怎样才能让它与共享指针一起工作呢?

【问题讨论】:

标签: c++ polymorphism overriding smart-pointers covariant-return-types


【解决方案1】:

只有指针/引用才有可能协方差。

对于智能指针,你必须“复制”接口:

class Base {
public:
    std::shared_ptr<Base> clone() const
    {
        return std::shared_ptr<Base>(vclone());
    }

    virtual ~Base() = default;
protected:
    virtual BaseSymbol* vclone() const = 0;
};
class Derived : public Base {
public:
    Derived(const Derived& derived);

    std::shared_ptr<Derived> clone() const
    {
        return std::shared_ptr<Derived>(vclone());
    }
protected:
    Derived* vclone() const override { return new Derived(*this); }
};

CRTP 可能有助于避免重写相同的模式。

【讨论】:

  • 至少使用std::make_shared(),并且让虚方法返回一个shared_ptr。开发一个允许模板选择加入协方差的功能会很有趣......
  • @Deduplicator:这需要强制转换(使用std::static_pointer_cast):-/ 从std::shared_ptr&lt;Base&gt;std::shared_ptr&lt;Derived&gt;:-/
  • @Jarrod42:根据现行规则,是的。但由于它们在结构上是等效的,因此可以更改规则。还是您的意思是更改为std::make_shared()?好吧,一个演员是值得的。
  • @Deduplicator:是your proposal吗?
  • 我的 cmets 确实是 std::make_shared。允许将类型标记为协变可能很好。或者也许它们只是“自定义”指针。
猜你喜欢
  • 2018-07-31
  • 2012-04-25
  • 2016-02-24
  • 1970-01-01
  • 2021-04-12
  • 2013-02-06
  • 2018-02-25
  • 1970-01-01
  • 2015-07-23
相关资源
最近更新 更多