c++ - 将派生类 unique_ptr 的所有权转移到其抽象基类 unique_ptr

标签 c++ unique-ptr

我想在多态情况下将派生类 unique_ptr 的所有权转移到它的抽象基类 unique_ptr。怎么走?

class Fruit {
public:
    virtual void print() = 0;
};

class Apple: public Fruit {
public:
    string name;
    virtual  void print()  { cout << " Apple name is " << name << endl; }
    Apple(string name): name(name) {}
};


int main()
{
    unique_ptr<Apple> apple = make_unique<Apple>("Rose");
    unique_ptr<Fruit> fruit = dynamic_cast<unique_ptr<Fruit>>(apple); // don't work
    // want to transfer ownership of apple to fruit

    unique_ptr<Apple> new_apple = dynamic_cast<unique_ptr<Apple>>(fruit); // get back the ownership to the new apple
    return 0;
}

最佳答案

转移由派生类管理的派生类的所有权unique_ptr到基类 unique_ptr ,您可以(并且应该)使用移动语义。

    std::unique_ptr<Derived> foo = std::make_unique<Derived>();
    std::unique_ptr<Base> bar = std::move(foo);

将所有权归还给派生的 unique_ptr ,你需要弄得更乱一些:

    std::unique_ptr<Derived> foo = std::make_unique<Derived>();
    std::unique_ptr<Base> bar = std::move(foo);

    std::unique_ptr<Derived> biz(static_cast<Derived*>(bar.release()));

如果您不确定指针的实际类型,则可以使用动态转换来检查它是否正确。请注意,我们使用 std::unique_ptr<Base>::get()在有条件的情况下,因为我们不确定我们是否要释放所有权。如果通过,那么我们可以调用std::unique_ptr<Base>::release() .

    std::unique_ptr<Derived> foo = std::make_unique<Derived>();
    std::unique_ptr<Base> bar = std::move(foo);

    // dynamic cast if we're unsure that it is castable
    if (dynamic_cast<Derived*>(bar.get())) {
        foo.reset(static_cast<Derived*>(bar.release()));
    }

see it in action

关于c++ - 将派生类 unique_ptr 的所有权转移到其抽象基类 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70457355/

相关文章:

c++ - 我应该从 main() 返回 EXIT_SUCCESS 还是 0?

c++ - 如何制作包含唯一指针的类的标准列表

c++ - diamond中无法通过std::unique_ptr访问最基类的protected成员变量

c++ - 使用 make_unique 语句重新分配 unique_ptr 对象 - 内存泄漏?

c++ - unique_ptr 编译错误

c++ - 将一个c++字符串分成两部分

c++ - 如何使用 std::filesystem 跳过/忽略名称使用宽字符的文件?

c++ - 如何编写一个给出两个参数最大值的 C++ 模板?

C++过滤调试事件

c++ - 错误::make_unique 不是 ‘std’ 的成员