如何在C ++'11中更改指针的所有权?

时间:2013-07-09 16:42:09

标签: c++ std move-semantics unique-ptr

我想使用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))
{
}

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

1 个答案:

答案 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))
{
}