[comp.lang.c++] more on "foo & operator+

Reid Ellis <rae@gpu.utcs.toronto.edu> (11/27/90)

In <fuchs.659473943@t500m0> fuchs@it.uka.de (Harald Fuchs) writes:
>I _never_ use
>  foo& operator+ (const foo&, const foo&)
>(returning a reference) because this can lead to dangling references.
>The returned value can't refer to an object on the stack because the
>stack is popped when returning from operator+. It cannot refer to a
>local static variable inside operator+ because in this case something like
>  foo f1 = f2 + f3 + f4;
>would give the wrong result.

Only if your operator+() assumed that none of the parameters could
ever be the result of a previous addition.  I agree that this
technique should be avoided if possible, but if you need the speed,
you can do it if you're careful.  e.g., for an integer class "Tint":

Tint& operator+(const Tint &left, const Tint &right)
{
	static Tint stat;

	stat.value = left.value + right.value;
	return stat;
}

This will never have a problem with either of 'l' or 'r' being the
result of a previous '+' -- i.e., a reference to 's'.

But I should state again that I agree that this should be avoided if
possible.  Be sure that doing this will really speed up your code by
profiling it before introducing something that could cause subtle
errors.

					Reid
--
Reid Ellis  176 Brookbanks Drive, Toronto ON, M3A 2T5 Canada
rae@gpu.utcs.toronto.edu      ||  rae%alias@csri.toronto.edu
CDA0610@applelink.apple.com   ||             +1 416 446 1644

jimad@microsoft.UUCP (Jim ADCOCK) (12/07/90)

In article <rae.659684428@earth| Reid Ellis <rae@gpu.utcs.toronto.edu> writes:
|Only if your operator+() assumed that none of the parameters could
|ever be the result of a previous addition.  I agree that this
|technique should be avoided if possible, but if you need the speed,
|you can do it if you're careful.  e.g., for an integer class "Tint":
|
|Tint& operator+(const Tint &left, const Tint &right)
|{
|	static Tint stat;
|
|	stat.value = left.value + right.value;
|	return stat;
|}
|
|This will never have a problem with either of 'l' or 'r' being the
|result of a previous '+' -- i.e., a reference to 's'.
|
|But I should state again that I agree that this should be avoided if
|possible.  Be sure that doing this will really speed up your code by
|profiling it before introducing something that could cause subtle
|errors.

??? I guess I don't understand what you're suggesting.  The above example
has [IMHO] unsubtle problems, consider:

	Tint a=100, b=200, c=300, d=400, e;
	e = (a + b) + (c + d);
	e.print();

results in 600 on my compiler [your compiler might give a different 
answer -- but its unlikely to be the 'right' one!]

Or is this what you mean by "subtle errors" ?