Why move around const objects?

I have a simple code:

const std::vector<int> data = {1,2,3}; std::vector<int> data_moved=std::move(data); for(auto& i:data) cout<<i;//output is 123 

It compiles without any errors or warnings.

and it seems that data still matters in it!

moving const values ​​doesn't seem right, because we can't modify const objects So, how does this code compile ?!

+7
c ++ c ++ 11 move-semantics move
source share
1 answer

You are not moving anything.

std::move really poorly named: it doesn't make you move; it just returns an rvalue. It is up to the compiler to decide which constructor std::vector<int> call, and what determines whether you exit.

If the container cannot be moved because the target move constructor is not a match, then the copy constructor will be used instead using the basic overload rules.

 #include <iostream> struct T { T() = default; T(const T&) { std::cout << "copy ctor\n"; } T(T&&) { std::cout << "move ctor\n"; } }; int main() { T a; T b = std::move(a); // "move ctor" const T c; T d = std::move(c); // "copy ctor" - `const T&&` only matches copy ctor // (shut up GCC) (void) b; (void) d; } 

( live demo )

He constructed this method ( const T&& ability to bind to const T& ), at least in part, because the move is for the best effort, just so that you don't have to deal with compiler errors in cases like this.

+9
source share

All Articles