Note: Chaining
assignments does not require references. It does not matter whether the value of cv3 is copied from reference to cv2 or from unnamed temporary copy.
Similarly, chaining additions does not require references:
cv4 = cv3 + cv2 + cv1;
Chained stream input and output does depend on non-const references though:
std::cout << "Hello" << " world";
is same as
(std::cout << "Hello") << " world";
is effectively same as
1 2
|
std::cout << "Hello";
std::cout << " world";
|
A reference is an alias; an alternative, additional name for a variable.
1 2 3 4
|
int foo = 7;
int & bar = foo;
bar = 42;
// value of foo is now 42
|
The caller of
CVector::operator= ()
can decide whether they create a reference to the returned object or make a copy. If the function would return a non-reference, then the caller would have only one option: to make a copy.
A example of common use of returned reference:
1 2
|
std::vector<int> gaz( 5 );
gaz[0] = 7;
|
The vector's []-operator returns a reference ...
Perhaps the CVector has other member functions too?
Let say it has a CVector::normalize() that changes the object.
Which looks more convenient?
1 2 3 4 5
|
cv2 = cv1;
cv2.normalize(); // cv2 is a normalized copy of the cv1
// or
(cv2 = cv1).normalize(); // cv2 is a normalized copy of the cv1
|
Probably the first one, but what if you should have all that within a conditional expression?