Hello !
I've read in a magazine "reference parameter in operator= must be const,
because in C++, temporary objects are const" and then my operator would
not work with temporary objets.
Well, sometimes it matters and sometimes it doesn't. Let's say you simply
define operator= as taking a T& as in the following test program:
#include <iostream>
using namespace std;
class T
{
public:
T();
T &operator=(T &) { cout << "In T:
perator=(T&)\n";
return *this; }
};
int main()
{
T t;
T t2;
t2 = t;
return 0;
}
It compiles and runs. So obviously either the magazine was wrong or you
misinterpreted what it said. I suspect it is the latter. The cases when
references must be declared const are when you bind them to constant
expressions, such as:
int const &ri = 10;
or:
void f(int &ri) {...}
...
f(10);
But, my compiler doesn't have temporary const objects.
I suspect it does.
Are there any
reasons to have a const reference parameter ?
The usual reason to show a ptr or ref parameter to /any/ function as ptr-to
-const or ref-to-const is for the benefit of "const correctness": to
"document" to the caller of the function that the argument in question will
not be modified. A reference-to-const or pointer-to-const parameter also
makes it possible for the argument passed in that position to actually have
a ptr-to-const or reference-to-const type. If we modify the definition of
t in main() above to be as follows:
const T t;
then the program will no longer compile. But changing the def of operator=
to:
T &operator=(const T &) { cout << "In T:
perator=(const T&)\n";
return *this; }
works in all cases, supports const correctness and allows const right-hand
expressions when using operator=. What's not to like?
-leor
..