Operator return type = - reference or value?

What is the difference between returning from the operator = function

by reference by value 

? Both versions seem to give the correct result in the example below.

 #include <iostream> using namespace std; class CComplexNumber{ float m_realPart; float m_imagPart; public: CComplexNumber(float r,float i):m_realPart(r),m_imagPart(i){} //the following can be also //CComplexNumber& operator=(const CComplexNumber& orig){ CComplexNumber operator=(const CComplexNumber& orig){ if (this!=&orig){ this->m_realPart=orig.m_realPart; this->m_imagPart=orig.m_imagPart; } return *this; } friend ostream& operator<<(ostream& lhs,CComplexNumber rhs){ lhs<<"["<<rhs.m_realPart<<","<<rhs.m_imagPart<<"]"<<endl; } }; int main() { CComplexNumber a(1,2); CComplexNumber b(3,4); CComplexNumber c(5,6); a=b=c; cout<<a<<b<<c; return 0; } 
+4
source share
2 answers

Return by value returns a copy of the object. Return by reference returns the object itself.

Which one you want to use depends on how you want to use the return value. If you want to change it without affecting the original object (after returning), return its value; otherwise, follow the link.

The convention when using the operator = member function is to return by reference. This allows you to chain operations on an object:

 CComplexNumber a(1,2); CComplexNumber b(3,4); (a = b) *= 2; //Assignment of b to a, then scale by 2 

Now, with a return by value after the assignment, *= will not change the value of a , since a copy of of will be scaled to 2. With a return by reference, b will be assigned a , and a will be scaled by 2.

+3
source

Link return (volatile) is the least surprising, and what you really have to choose for the operation that is so common is implicitly declared. A reference is the return type of implicit definitions by default.

Example:

 A operator=(const A&) = default; // ERROR const A& operator=(const A&) = default; // ERROR A& operator=(const A&) = default; // OK 

Some compilers will kindly warn you if you do not return the link in a user-defined function.

In addition to an unexpected (and sometimes expensive) copy, it also avoids slicing.

Returning a const reference may prohibit movement.

+2
source

Source: https://habr.com/ru/post/1494350/


All Articles