Search code examples
c++linuxc++11move

c++11 move not take effective?


I tested c++11 move function, but not become effective. Who can tell me why ? Thanks. The code is as follows:

class Base {
  public:
   Base() { cout << "Base" << endl;}
   ~Base() { cout << "~Base" << endl;}

   Base(const Base& base) { cout << "Copy" << endl; }
   Base& operator=(const Base& base) {cout << "operator=" << endl;}

   Base(Base&& base) { cout << "move" << endl;}
   Base& operator=(Base&& base) { cout << "move=" << endl;}
};

Base b;

Base&& GetResult() {
  return std::move(b);
} 

int main() {
Base&& tmp = GetResult();

cout << &b << endl;
cout << &tmp << endl;

}

Output:

 Base
 0x6013a0
 0x6013a0
 ~Base

Why move copy and move operator= not be called ? And why address is the same ?


Solution

  • To add to the excellent existing answers, I believe the main point of confusion here is what std::move does.

    std::move does not move.

    It was abysmally named.

    It only gives you an xvalue referring to whatever you gave it; this xvalue will bind to a rvalue reference where an lvalue won't. This means the result of std::move can be given to a move constructor or move assignment operator. However, it does not do that for you, and you do not do it here.


    Given such strong criticism for the naming, surely you have an alternative suggestion
    user2079303

    This is a well-trodden topic, but the creator of C++ suggests std::rval, and one of the architects of modern C++ suggests std::rvalue_cast (even though you actually get an xvalue).

    Personally, I think std::moveable would have been a nice middle ground.