c++ - 指向来自基类的派生类的 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
我怎样才能使这项工作?
解决方案
如果您想引用代码中其他地方拥有的对象,这是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;
}
请注意,上述解决方案可能会导致两次释放相同指针的不良行为。
推荐阅读
- python - How to write content of an array to a text file, one data on each line?
- r - How can I append a result in a vector without overwriting? (loop)
- flutter - Flutter:更新滚动视图物理而不重建
- iframe - iframe 为 Grafana 显示“拒绝连接”
- java - 如何在正则表达式 Jlex 中选择特定单词?
- mysql - 将字符串从 MySQL 转换为 JSON,意外的令牌 N
- reactjs - React.js:登录时如何获取并显示当前用户?
- python - 从 Cygwin 扫描 Windows 中的驱动器
- macos - 为什么 /usr/libexec/java_home 不打印任何内容?
- python - Python Pandas:使用 apply 方法从另一个数据框中更新多个列值