首页 > 解决方案 > 指向来自基类的派生类的 std::unique_ptr 的指针

问题描述

我正在尝试制作一个std::unique_ptr<BaseClass>*可以指向任何std::unique_ptr<DerivedClass>.

我有以下类层次结构:

[InputHandler] <--inherits from-- [DrawingTool] <--inherits from-- [ToolName]

以及以下代码:

std::unique_ptr<DrawingTool> *active_tool;
active_tool = tool_manager.getCurTool();   // Returns a unique_ptr<DrawingTool>*

std::unique_ptr<InputHandler> *cur_input_handler = active_tool;

然而,这给出了错误:

 error: cannot convert ‘std::unique_ptr<DrawingTool>*’ to ‘std::unique_ptr<InputHandler>*’ in initialization

我怎样才能使这项工作?

标签: c++pointerspolymorphismsmart-pointersc++-standard-library

解决方案


如果您想引用代码中其他地方拥有的对象,这是std::shared_ptr您的方式(至少如果您想实现您在示例中显示的内容,这是您问题的一部分)。然后,如果要将基类向下转换std::shared_ptr为派生类std::shared_ptr,可以执行以下操作:

#include <iostream>
#include <memory>

struct Base {};

struct Derived : Base {};

int main() {
    std::shared_ptr<Base> base = std::make_shared<Base>();
    std::shared_ptr<Derived> derived = std::static_pointer_cast<Derived>(base);

    return 0;
}

此外,以下代码可能会模仿您的情况以及您想要更好地实现的目标:

#include <iostream>
#include <memory>

struct Base {};

struct Derived : Base {};

std::unique_ptr<Base> const& get_unique_ptr() {
    static std::unique_ptr<Base> base = std::make_unique<Base>();
    return base;
}

int main() {
    std::unique_ptr<Base> const& base = get_unique_ptr();
    std::unique_ptr<Derived> derived(static_cast<Derived*>(base.get()));

    return 0;
}

请注意,上述解决方案可能会导致两次释放相同指针的不良行为。


推荐阅读