Why does calling std::move on a const
object call the copy constructor when passed to another object? Specifically, the code
#include <iostream>
struct Foo {
Foo() = default;
Foo(Foo && x) { std::cout << "Move" << std::endl; }
Foo(Foo const & x) = delete;
};
int main() {
Foo const x; Foo y(std::move(x));
}
fails to compile with the message:
g++ -std=c++14 test07.cpp -o test07
test07.cpp: In function 'int main()':
test07.cpp:10:36: error: use of deleted function 'Foo::Foo(const Foo&)'
Foo const x; Foo y(std::move(x));
^
test07.cpp:6:5: note: declared here
Foo(Foo const & x) = delete;
^
Makefile:2: recipe for target 'all' failed
make: *** [all] Error 1
Certainly, I expect it to fail because we can't move a const
value. At the same time, I don't understand the route that the code takes before it tries to call the copy constructor. Meaning, I know that std::move
converts the element to an x-value, but I don't know how things proceed after that with respect to const
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…