What to use: move the assignment operator and copy assignment operator

I don't seem to understand why you are using move assignment operator:

CLASSA & operator=(CLASSA && other); //move assignment operator

copy assignment operator:

CLASSA & operator=(CLASSA  other); //copy assignment operator

move assignment operatoronly accepts r-value referencefor example

CLASSA a1, a2, a3;
a1 = a2 + a3;

In copy assignment operator, othercan be constructor using copy constructoror move constructor(if otherinitialized r value, it can be designed for movement --if move-constructor-).

If this is the case copy-constructed, we will make 1 copy and this copy cannot be avoided.

If it is move-constructed, then the performance / behavior is identical to the performance created by the first overload.

My questions:

1- Why you need to implement move assignment operator.

2- If otherconstructed by r-value, then which assignment operatorcompiler could call? And why?

+4
2

, std::unique_ptr, .

, , , , .

  • T& operator=(T const&)
  • T& operator=(T const&) T& operator=(T&&)
  • T& operator=(T)

, , , , .

1 ++ 98 . , r, 2 .

3 , , , , . . l- r, .

" ! ++" CppCon 2014, . l- . . - , , , .

, 1 2, r-.

+4

, :

  • , rvalue, r . lvalues, , , T const& . , , std::unique_ptr<T>, .
  • , , rvalue, lvalue, , , . swap(), . , / .

, ! lvalue, , , ( ). r, .. . , :

struct foo
{
    void operator=(foo&&) {}
    void operator=(foo) {}
};

int main()
{
    foo f;
    f = foo();
}

, , T&& T const& . , , T , .

, :

  • T::operator= (T&&).
  • T::operator=(T).
+2

All Articles