c++ - 将 unique_ptr<Derived> 转换为 unique_ptr<Base>

标签 c++ pointers unique-ptr

一个简单的代码

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

但这也不起作用(编译错误),而且它也不是 recommendednew 与智能指针一起使用。

什么是正确的解决方案?

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

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/

相关文章:

c++ - 内存释放双向链表C++

c++ - 对于使用C++ 20破坏运算符delete的非多态派生类,则为unique_ptr

c++ - 指向 STL 容器的指针安全吗?

c++ - 为什么我在包含 windows.h 时收到错误 "WM_MENUCOMMAND was not declared in this scope"?

c++ - Ogre3d 场景节点数组

c++ - 如何将 vtkImageData 转换为 cv::Mat?

pointers - Box、ref、&和*的理解和关系

c++ - 我如何能够在 C++ 中声明一个在运行时确定的可变长度数组?

c++ - 列表中指针的问题

c++ - 编译但失败的 C++ std::vector<std::auto_ptr<T>> 示例