Quick Q: Why does trying to use a std::move'd object try to copy? -- StackOverflow

Quick A: Think of move is (mostly) an optimization of copy, and copy as the "slow" fallback when you can't actually move.

Fresh on SO:

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.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.