我想使用unique_ptr<NativeWindow>
存储指向我的本机窗口实例的指针,以便在Window
对象超出范围时保证释放它。
// This would be maintained by a window manager
unique_ptr<Window> window;
void Foo() {
NativeWindow *pNativeWindow = createNativeWindow();
window = new Window(pNativeWindow);
}
// ...
class Window {
private:
unique_ptr<NativeWindow> _nativeWindow;
public:
inline NativeWindow& GetNativeWindow() {
return *_nativeWindow;
}
// ...
Window::Window(NativeWindow&& nativeWindow)
: _nativeWindow(std::move(nativeWindow))
{
}
我很难理解移动语义,并且会发现从这个例子中学习起来更容易。如果这是香草指针,我会没事的,但我想了解新方法!
答案 0 :(得分:2)
Window
构造函数应该是NativeWindow *
,而不是NativeWindow&&
。
Window::Window(NativeWindow* nativeWindow)
: _nativeWindow(nativeWindow)
{
}
这应该可行,但我建议您将参数更改为unique_ptr<NativeWindow>
。这清楚地表明Window
对象假定拥有NativeWindow
参数。
Window::Window(std::unique_ptr<NativeWindow> nativeWindow)
: _nativeWindow(std::move(nativeWindow))
{
}