Search code examples
c++c++11move

What is the advantage of a move constructor over a copy constructor that takes a bool that says whether to copy or move?


Why do we need a move constructor/assignment operator in C++ when we can just do this:

Foo(const Foo& x, bool copy = false) {
    if (copy) {
        // copy
    }
    else {
        // move
    }
}

or am I missing something?


Solution

  • Move constructors are implicitly written for you (unless you block it).

    Move constructors are called automatically for you in certain contexts, even if you have code written before they existed.

    Move only types can exist with move constructors, and they block copy-actions with an error at compile time.

    Marking something as 'please move from this' does not require a 2nd parameter, making perfect forwarding work. Perfect forwarding also just works with rvalues. (perfect forwarding is imperfect, btw)

    Move assignment won't work well well with your pattern.

    The rvalue ref is useful in contexts outside of move/assign.

    Honestly, comparing C++11 move and rvalue refs to your proposal is like asking why a Telsa is better than a tricycle with a broken wheel. The broken trike is cheaper, I will grant it.