c++ 14(VS 2015)中带有受保护继承的shared_ptr – 无适用的用户定义转换。

huangapple go评论67阅读模式
英文:

c++ 14 (VS 2015) shared_ptr with protected inheritance - no suitable user defined conversion

问题

我在使用受保护继承时,使用共享指针出现了奇怪的编译错误。下面这段简单的代码无法编译,出现错误 "没有合适的用户定义转换",但在使用公共继承时可以正常工作。不确定原因,有人能解释一下吗?

class ioptionpricer
{
public:
    virtual std::shared_ptr<ioptionpricer> clone() const = 0;
    virtual void doSomething() const = 0;
    virtual ~ioptionpricer() = default;
};

class optionpricer : protected ioptionpricer
{
public:
    std::shared_ptr<ioptionpricer> clone() const
    {
        return std::make_shared<optionpricer>(*this);
    }
};
英文:

I'm getting a strange compilation error when using shared pointer with protected inheritance. The below simple code doesn't compile and gives error "no suitable user defined conversion" but it works with public inheritance. Not sure why, could anyone please explain?

class ioptionpricer
{
public:
    virtual std::shared_ptr&lt;ioptionpricer&gt; clone() const = 0;
    virtual void doSomething() const = 0;
    virtual ~ioptionpricer() = default;
};

class optionpricer : protected ioptionpricer
{
public:
    std::shared_ptr&lt;ioptionpricer&gt; clone() const
    {
        return std::make_shared&lt;optionpricer&gt;(*this);
    }
};

答案1

得分: 1

当继承是私有的(或受保护的),则在类外部(或受保护继承的派生类)无法将 derived* 强制转换为 base*

在将 shared_ptr&lt;derived&gt; 转换为 shared_ptr&lt;base&gt; 时,derived*base* 的转换发生在 shared_ptr&lt;T&gt; 模板的实现中。因此,使用私有/受保护继承不可行,除非将 shared_ptr 声明为友元。

无论如何,在这些情况下只需使用 public 继承,将其设为私有或受保护在这种情况下是没有意义的。

英文:

When the inheritance is private (or protected) then one cannot cast derived* to base* outside of the class (or derived classes for protected inheritance).

In case of conversion from shared_ptr&lt;derived&gt; to shared_ptr&lt;base&gt;, the conversion from derived* to base* happens somewhere in implementation of the template shared_ptr&lt;T&gt;. So, with private/protected inheritance it won't fly. Unless you declare shared_ptr to be a friend.

Either way just use public inheritance in these situations, it is pointless to make it private or protected in such situations.

huangapple
  • 本文由 发表于 2023年5月7日 07:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定