【发布时间】:2020-01-27 21:20:34
【问题描述】:
我正在尝试创建一个可以指向任何std::unique_ptr<DerivedClass> 的std::unique_ptr<BaseClass>*。
我有以下类层次结构:
[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::unique_ptr的指针? -
听起来你要么想要一个原始指针,要么想要一个
shared_ptr。您似乎不想拥有该工具的所有权,因此DrawingTool * active_tool;在这里可能会更有用。 -
请注意
some_template_type<T>与some_template_type<U>是完全不同的类型。 -
@NutCracker 我对 C++ 很陌生,所以也许我采用了错误的方法 - 但我的想法是我不想共享类的所有权(使用原始指针或 shared_ptr ),我只想引用一个在别处拥有的类。
-
@JShorthouse:“我只想引用一个在别处拥有的类。”但这只是传递一个引用。或原始指针。
标签: c++ pointers polymorphism smart-pointers c++-standard-library