To understand why your code does not compile, reflect how you have declared Foo
class and how move semantics
is generally implemented.
Declaring a const unique_ptr<T> p
, you mean that p
itself will be never modified, but you could still modify the pointed-to object because of T
is not const.
But move
works on an opposite assumption. This feature uses the idea that is allowed stealing resources from objects and leave them in a empty state (if an empty state make sense). If can be useful, think move
as a sort of 'destructive' copy for the moved object.
Writing std::move(foo.p)
, basically you steal the resource pointed by foo.p
and leave it in a safe state, that means assign foo.p
to NULL
. But foo.p
was declared as const, so the operation is not permitted.
Please consider that in your case you don't need to declare p as a const unique_ptr<int>
. Simply declare it as unique_ptr<int>
and make sure that member functions are declared as const
and non-member functions take it asconst unique_ptr<int> p&
parameter. In this way you are sure that p
will never change along the object lifetime (except in case of move operation).