繁体   English   中英

转换 unique_ptr<Derived> 到 unique_ptr<Base>

[英]Convert unique_ptr<Derived> to unique_ptr<Base>

一个简单的代码

class Base {};
class Derived : Base {};

unique_ptr<Base> Create() {
    unique_ptr<Base> basePtr = make_unique<Derived>(); // compile error
    return basePtr;
}

产生编译错误(“没有合适的转换”)。 我发现了类似的问题,解决方案是使用std::move 我试过这个

unique_ptr<Derived> derived = make_unique<Derived>();
unique_ptr<Base> basePtr = std::move(derived); // compile error

但现在std::move产生编译错误。 我还发现了一个问题(如果我理解得很好)如果我们使用演员表应该是自动的

unique_ptr<Base> basePtr = make_unique<Derived>(new Derived()); //compile error

但这也不起作用(编译错误),也不建议new与智能指针一起使用。

什么是正确的解决方案?

到目前为止我发现的唯一可行的解​​决方案

unique_ptr<Base> basePtr = unique_ptr<Base>((Base*)new Derived());

看起来真的很丑。

您的类是从基类私下继承的。 这是class的默认值,而struct的默认值是公共继承。 这使得外部派生到基础的转换无效。 unique_ptr使用公共继承处理派生到基本的转换( 实例 ):

 class Base {};
 class Derived : public Base {};
                 ^^^^^^

如下所述,在使用unique_ptr时向基类添加虚拟析构函数也很重要,因为多态破坏依赖于此来定义明确的行为。 shared_ptr不会要求这个,但那是偏离主题的。

该模式在 pimpl 惯用语中经常使用,因此需要使用虚拟析构函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM