【发布时间】:2017-07-24 21:58:21
【问题描述】:
有没有办法从继承的类之一创建unique_ptr?
我需要能够向经理“注册”MouseListeners,但我不知道如何创建继承的MouseListener 的unique_ptr。
错误是找不到从Window * 到MouseListener 的转换。我尝试了static_cast,但这会产生其他错误。我还尝试将raw pointer 传递给addMouseListener,它确实有效,但在您关闭程序时出错,因为我认为它没有创建导致delete 失败的适当内存。
还使用std::move() 转移所有权,导致监听器不触发事件。
// Window.h
class Window : public MouseManager, public MouseListener {
public:
Window::Window(std::string title, int32_t width, int32_t height) {
...
this->addMouseListener(std::make_unique<MouseListener>(this)); // ERROR
}
};
// MouseManager.h
void MouseManager::addMouseListener(std::unique_ptr<MouseListener> listener) {
m_listeners.emplace_back(listener);
}
// MouseListener.h
MouseListener() = default;
virtual ~MouseListener() = default;
MouseListener(const MouseListener& listener) = default;
MouseListener(MouseListener&& listener) noexcept ;
MouseListener& operator=(const MouseListener& listener) = delete;
MouseListener& operator=(MouseListener&& listener) = delete;
错误输出
In file included from /Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.cpp:5:
In file included from /Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.h:8:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:3141:32: error: no matching constructor for initialization of 'MouseListener'
return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/Window.cpp:17:33: note: in instantiation of function template specialization 'std::__1::make_unique<MouseListener, Window *>' requested here
this->addMouseListener(std::make_unique<MouseListener>(this));
^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:19:5: note: candidate constructor not viable: no known conversion from 'Window *' to 'const MouseListener' for 1st argument; dereference the argument with *
MouseListener(const MouseListener& listener) = default;
^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:20:5: note: candidate constructor not viable: no known conversion from 'Window *' to 'MouseListener' for 1st argument; dereference the argument with *
MouseListener(MouseListener&& listener) noexcept ;
^
/Users/Programmer/CLionProjects/StormEngine/Engine/Window/../Events/Listeners/MouseListener.h:16:5: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
MouseListener() = default;
^
更新:
取消引用this 增加了一个新问题,其中添加变量listener 你必须添加到std::move(),这会导致所有权更改,如上所述导致事件不触发。
【问题讨论】:
-
1.你读过错误信息吗? 2. 创建minimal reproducible example。
-
我指定了这个实现的错误。 "它找不到从
Window*到MouseListener的转换。我将发布错误日志以更加清楚,以防人们错过它。 -
MouseListener的构造函数是什么? -
这三个都显示在错误日志中。如果需要,我可以将其添加到问题中。
-
@Matthew 您需要添加所有类型的定义。但是删除不需要演示问题的类型的使用。如果不需要,也删除定义的部分。换句话说,创建一个minimal reproducible example。
标签: c++ inheritance unique-ptr