Search code examples
c++11move

C++11 move assignment operator for classes with objects as members - Beginner Level


I have a beginner question on the move assigment in c++11. Let say that I have a class A provided with a move assigment operator:

class A
{
 public:
   A();
  ~A();
  A& operator=(A&&);
  ...
}

I also have a class B containing a class A object and provided with a move assignment operator

class B
{
 public:
     B();
    ~B();
   B& operator=(B&&);
    ...
 private:
   A Test;
}

What I was thinking is that the B move assignment operator will call the move assignment operator of its member so I tried this method:

B& B::operator=(B&& Other)
{
  ...
  Test = Other.Test;
  ...
  return *this;
}

But this is not working since the move assignment of class A is not called.

Instead I was able to make the program work by using this method:

B& B::operator=(B&& Other)
{
  ...
  Test = std::move(Other.Test);
  ...
  return *this;
}

I do not understand why the first method is not working. I was thinking that since a constructor will call its members constructors the move assignment operator should do the same. Am I wrong or I made a mistake in my code? Can someone explain, thanks!


Solution

  • Other.Test is not an rvalue expression since it has a name. OTOH std::move(Other.Test) has the type A and the value category xvalue (i.e., an rvalue). Thus, it can bind to the move constructor.

    (EDIT : Shamelessly copied @dyp's comment. Thanks, @dyp and @KerrekSB.)