Operator overloads are just like any other member function, you
can make them do whatever you want. However, of course, we might
expect them to behave in a certain way. The ++ operator should perform
some sort of increment, the / operator should do something along the
lines of division.
Do you think it would have been worthwhile for the C++ Standard to
"codify" this expected use of operator overloads? I'll be specific:
Let's say you overload the ++ operator, both the pre and the post
form. In our class, they both behave as expected: The pre gives you
the new value, the post gives you the old value. In our particular
implementation, the pre version is much more efficient that the post
version because the post version involves the creation of a temporary
(and let's say our class object is quite expensive to construct).
Let's say we have code such as the following:
for (OurClass obj = 0; obj < 77; obj++) DoSomething;
When the compiler looks at this, it can see straight away that the
result of the incrementation is discarded. If it has some sort of
"codified expected usage" of operator overloads, it could invoke "+
+obj" instead.
Similarly, if you had a function such as:
void Func(ClassObject const arg)
{
return arg * 7 - 2;
}
it could treat it as:
void Func(ClassObject arg)
{
arg *= 7;
arg -= 2;
}
thus getting rid of temporary objects.
If there was a "codified expected usage" then I don't think it
would be too far removed from the current situation we have with
contructor elision. With constructor elision, the compiler just
assumes that the creation of a temporary object won't result in
something important happening like a rocket being sent to the moon, so
it just gets rid of the temporary. For it to have this "way of
thinking" though, the Standard basically had to say "well constructors
aren't supposed to do something important outside of the object". This
wouldn't be very different at all from saying "Well the pre-increment
should be indentical to the post-increment if the result is
discarded".
The net result of this is that code could be written more naturally;
for instance take the following function:
void Func(int const i)
{
return i * 7 - 2;
}
If we introduce a class object, it could be left as:
void Func(OurClass const i)
{
return i * 7 - 2;
}
instead of having to change it to:
void Func(OurClass i)
{
i *= 7;
i -= 2;
return i;
}
But then again, even if the Standard did have some sort of expected
usage of operator overloads, they're probably still be people who
wouldn't trust the compiler to do the right thing.