Reputation: 64196
I would like to store a pointer to my native window instance using unique_ptr<NativeWindow>
so that it is guaranteed to be freed when Window
object goes out of scope.
// 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))
{
}
I am having a hard time understanding the move semantics and would find it easier to learn from this example. If this were vanilla pointers I would be fine, but I am trying to understand the new way!
Upvotes: 0
Views: 621
Reputation: 109119
The Window
constructor should be taking a NativeWindow *
, not NativeWindow&&
.
Window::Window(NativeWindow* nativeWindow)
: _nativeWindow(nativeWindow)
{
}
That should work, but I suggest you change the parameter to unique_ptr<NativeWindow>
instead. This makes it clear that the Window
object is assuming ownership of the NativeWindow
argument.
Window::Window(std::unique_ptr<NativeWindow> nativeWindow)
: _nativeWindow(std::move(nativeWindow))
{
}
Upvotes: 2