Why does the following code compile?
#include <vector>
#include <iostream>
struct Foo {
std::vector<int> bar = {1, 2, 3};
};
int main()
{
Foo foo1;
const Foo& foo2 = foo1;
std::vector<int> target;
std::move(foo2.bar.begin(), foo2.bar.end(), std::back_inserter(target));
return 0;
}
The documentation of std::move says
After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.
So this can actually change the object foo2 even though it's declared const. Why does this work?
const
, so you are preventing to change the reference of that variable. Sincevector<>
points to the another block of memory you can tweak it on your own. If you want to prevent that vector for changes mark it as const:const vector<int> nums {1, 2, 3}
– Uniflorousbar
is aconst std::vector<int>
thestd::move
is allowed. – Sturdivantmutable
). Similarly, a struct being const transfers that property to its content. So indeed, that question is very justified in my opinion! – Maddalena