Search code examples
c++move

Why is an object not moved if += is in the return statement


I imitated std::vector::operator+() from Visual Studio. It looks similar to this:

A operator+(const int diff) const {
    A temp = *this;
    return temp += diff;
}

Though I have a move constructor, it uses the copy constructor, but when I use this:

A operator+(const int diff) const {
    A temp = *this;
    temp += diff;
    return temp;
}

It does actually move. Why is this?


Solution

  • The article below explains it, but in short:

      1. example: returns a reference and the compiler can't be convinced the value isn't used elsewhere.
      1. example: returns a locally created value and is safe to move.

    You can also fix it by returning std::move(temp += diff), but this is often not preferred as it prevents the compiler from using Return Value Optimization (RVO).

    https://web.mst.edu/~nmjxv3/articles/move-gotchas.html

    Why Visual Studio doesn't take this in account, I don't know.