tom_usenet posted:
No, it *can* just use the one from the calling function - that's the
whole point of passing it by value. See 12.8/15 of the standard.
If that's true, then in the *your* code, you're changing the original.
We haven't got an operator+= here, we've got an operator+.
But alas, the original remains unchanged. Why? because "lhs" is *NOT* the
original object from the calling function, it's a local non-const object
which has been copy-constructed from the supplied object in main, and as
such, you can do whatever you like with it, including an operator+=!
C operator+(C lhs, const C& rhs)
{
return lhs += rhs;
}
"lhs", before any of the body of code is executed, is copy contructed from
the object supplied in the calling function.
Let's examine the two samples. If you don't mind, I'm going to change the
name of the class, it's distracting me. *Your* sample:
Monkey operator+(Monkey lhs, const Monkey& rhs)
{
return lhs += rhs;
}
And *my* sample:
Monkey operator+(const Monkey& lhs, const Monkey& rhs)
{
Monkey temp_monkey(lhs);
return temp_monkey += rhs;
}
Before going further, my argument is *NOT* that either sample is superior,
but that *neither* is superior.
Here's some code that'll work with objects of our class:
int main()
{
Monkey pet_monkey(5); //Let's pretend it has such a constructor
Monkey wild_monkey(18);
Monkey domesticated_monkey(pet_monkey + wild_monkey);
}
When *your* code is called, a Monkey object is copy-constructed from
"pet_monkey" before the body of the "operator+" function is executed. So now
you can do whatever you want with this "copy", and evidently you *are*,
you're changind it, you're performing a += on it. You argue that you're
working with the original object from the calling function; if this is so,
then the original object would be changed by the +=.
Answer: The original object isn't changed because you're not *working* with
the original object, you're working with a non-const local object in the
operator+ function.... which has been copy-constructed from the pet_monkey
object in main(). When the operator+ fuction comes to the end of its
execution, the local "copy" is destroyed.
When *my* code is called, (assuming a stack and register system), my
operator+ function will be supplied with two "hidden pointer"s. Then, I
define a local non-const object, which I copy-construct from pet_monkey.
Then I do a += on this "copy". My "copy" is destroyed when the operator+
function reaches the end of its execution.
So, with *your* code:
Copy-constructed object
operator+=
Destruction of copy-constructed object
with *my* code:
Copy-constructed object
operator+=
Destruction of copy-constructed object
-JKop