[comp.lang.c++] "foo operator+

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

ahodgson@hstbme.mit.edu (Antony Hodgson) writes:
>Just a warning that the use of the expression:
>
>	foo& operator + ( foo& f )
>or
>	friend foo& operator + ( foo& f1, foo& f2 )
>
>will almost invariably lead to a run-time error. ... 
> ... It's much better to define the operator as
>
>	foo operator+(foo& f)
>
>and let the system deal with deallocating it when it goes out of scope.

If the object if large, it is sometimes desirable to maintain a static
instance within the operator method and return a reference.  e.g.:

	foo & foo::operator+=(const foo &f) { ... }

	foo & foo::operator+(const foo &f)
	{
		static foo sf;

		sf = *this;
		return sf += f;
	}

This is a variation on the standard "use the stack" method of
operator+().  The only way to get "caught" using this is if you hold
the return value in a reference, as in:

	foo &rf = foo1 + foo2;

<Personal Opinion ON>
	I consider this poor form myself.  If you had defined the add
	method as "foo foo::operator+(..)" then you would be creating a
	reference to a temporary.
<Personal Opinion OFF>

						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

chip@tct.uucp (Chip Salzenberg) (11/28/90)

According to Reid Ellis <rae@gpu.utcs.toronto.edu>:
>	foo & foo::operator+=(const foo &f) { ... }
>
>	foo & foo::operator+(const foo &f)
>	{
>		static foo sf;
>
>		sf = *this;
>		return sf += f;
>	}
>
>The only way to get "caught" using this is if you hold
>the return value in a reference, as in:
>
>	foo &rf = foo1 + foo2;

I believe that:

    foo f = (foo1 + (foo2 + foo3));

is likely to break using the reference-to-static trick.