Assignment Operator, Returning const reference
Ok, so let's say I have the following class:
class A
{
public:
A();
A(int data) : m_data(data) {}
const A& operator=(const A& rhs);
private:
int m_data;
};
At first glance, I would assume that returning a const reference from
an overloaded assignment operator would generate compiler errors
if you attempted to chain assignments, say a1=a2=a3, but to my surprise,
I tried it and the compiler did not complain. My question is, what are the consequences of returning a const reference from an assignment operator rather than just a regular reference?
# 1 Re: Assignment Operator, Returning const reference
In this case it doesn't matter much because when youi have a=b; you actually have
a.operator=(b); where b is const anyway, and a isn't. However, when the function call returns, a is returned is a reference to const, which is then used as the argument of another operator= call, which in turn takes a reference to const argument.
So in this case, returning a reference to const isn't a problem but it could become a problem in other scenarios, e.g, when the resulting reference is assigned to a non-const reference:
A& ref=(a=b); //error
Danny at 2007-11-11 21:01:40 >

# 2 Re: Assignment Operator, Returning const reference
Ok, thanks, that makes more sense.
I guess I wasn't thinking right about how a chained assignment works.
# 3 Re: Assignment Operator, Returning const reference
Just in case you want to know why we need to return const reference--
To avoid extra copying and an implicit call to the copy constructor, we make the return value a constant reference parameter,
# 4 Re: Assignment Operator, Returning const reference
Just in case you want to know why we need to return const reference--
To avoid extra copying and an implicit call to the copy constructor, we make the return value a constant reference parameter,
In the case of an assignment operator, this isn't exactly the reason. You simply have no other choice since operator= must return a reference, never a value object. The question is whether the return value should reference to const or plain reference. Normally, it's the former.
Danny at 2007-11-11 21:04:45 >

# 5 Re: Assignment Operator, Returning const reference
Hi,
I just made a li'l experiment and changed the return type of my assignment operator from 'ref' to 'object'. It still compiles and when stepping through, the operator is still called! Is it (again) VS6.0 playing up or what happens here? Is it expected, that the operator is called but the result is something other than I would expect?
D
# 6 Re: Assignment Operator, Returning const reference
It will work but it could create serious bugs such as assigning a reference to a dangling object:
A & ref= b=c;
Which would bind a temporay (i.e., the object returned by value from operator=) to ref.
Danny at 2007-11-11 21:06:54 >
