![](/img/trans.png)
[英]Cannot convert unique_ptr<derived> to 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.