0

我想使用存储一个指向我的本机窗口实例的指针,以便在对象超出范围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))
{
}

我很难理解移动语义,并且会发现从这个例子中学习起来更容易。如果这是香草指针,我会很好,但我正在尝试理解新方法!

4

1 回答 1

2

构造Window函数应该采用 a NativeWindow *,而不是NativeWindow&&

Window::Window(NativeWindow* nativeWindow)
    : _nativeWindow(nativeWindow)
{
}

那应该可以,但是我建议您将参数更改为unique_ptr<NativeWindow>。这清楚地表明该Window对象正在假设参数的所有权NativeWindow

Window::Window(std::unique_ptr<NativeWindow> nativeWindow)
    : _nativeWindow(std::move(nativeWindow))
{
}
于 2013-07-09T16:55:44.663 回答