I have code as following
std::vector<std::unique_ptr<int>> v;
std::unique_ptr<int> a(new int(0));
std::unique_ptr<int>& b = a;
v.insert(v.begin(), std::move(b)); //ok
However if I add const in the third statement
const std::unique_ptr<int>& b = a;
v.insert(v.begin(), std::move(b)); //Compiler error, cannot access ptr private member
Why does the compiler show it cannot access private member of the unique pointer other than cannot convert const to non-const? Thanks.
You cannot move a
constobject. Moving means altering the state of the object you moved from (of whatever type that object is), and declaring it asconstmakes a promise that you won’t alter that state. Thus, moving aconstobject is a contradiction in terms.Although the expectation of being able to move a
constobject may indeed have some kind of justification (for instance, you may want the object to beconstas long as you use it, and then get rid of it when you’re done and transfer its guts rather than copying it – which is btw impossible with aunique_ptr), actually allowing this would have a number of very impractical semantic consequences (for instance, it would allow swapping twoconstobjects).Thus, even though the language does technically allow moving from a
constobject (move constructors accepting aconstRRef are legal), no type of the Standard Library actually gives you that possibility, includingunique_ptr, and you should not write any UDT that does.Conceptually, it is really important to think of moving as a state-altering operation, which is not compatible with the
constmodifier.