一个简单的代码
class Base {};
class Derived : Base {};
unique_ptr<Base> Create() {
unique_ptr<Base> basePtr = make_unique<Derived>(); // compile error
return basePtr;
}
产生一个编译错误(“没有合适的转换”)。我找到了 similar question解决方案是使用 std::move
。我试过了
unique_ptr<Derived> derived = make_unique<Derived>();
unique_ptr<Base> basePtr = std::move(derived); // compile error
但现在 std::move
会产生编译错误。我还找到了question如果我们使用
unique_ptr<Base> basePtr = make_unique<Derived>(new Derived()); //compile error
但这也不起作用(编译错误),而且它也不是 recommended将 new
与智能指针一起使用。
什么是正确的解决方案?
到目前为止我找到的唯一可行的解决方案
unique_ptr<Base> basePtr = unique_ptr<Base>((Base*)new Derived());
看起来真的很丑。
最佳答案
您的类是从基类私有(private)继承的。这是 class
的默认值,而 struct
的默认值是公共(public)继承。这使得外部派生到基础的转换无效。 unique_ptr
通过公共(public)继承 ( live example ) 很好地处理派生到基础的转换:
class Base {};
class Derived : public Base {};
^^^^^^
如下所述,在使用 unique_ptr
时向基类添加虚拟析构函数也很重要,因为多态析构依赖于此来实现明确定义的行为。 shared_ptr
不需要这个,但这离题了。
关于c++ - 将 unique_ptr<Derived> 转换为 unique_ptr<Base>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51209700/