Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!usc!snorkelwacker.mit.edu!bloom-beacon!hstbme.mit.edu!ahodgson From: ahodgson@hstbme.mit.edu (Antony Hodgson) Newsgroups: comp.lang.c++ Subject: Re: friend operator +(l,r) vs. operator +(r) Summary: Warning about using foo& operator+( foo& f ) Message-ID: <1990Nov22.001208.26092@athena.mit.edu> Date: 22 Nov 90 00:12:08 GMT References: <11759@hubcap.clemson.edu> <1990Nov21.140621.4229@ssd.kodak.com> <11782@hubcap.clemson.edu> Sender: daemon@athena.mit.edu (Mr Background) Reply-To: ahodgson@hstbme.mit.edu.UUCP (Antony Hodgson) Organization: Massachusetts Institute of Technology Lines: 27 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. The obvious interpretation of the + operator is that you are creating a new object from the two arguments. This new object will therefore require its own storage. You can either do this by defining a foo variable local to the + function, or by using "new" to create a new one inside +. If you do the former, you return a reference to an object which is susceptible to being immediately deallocated, so any use of the foo& outside of + will give garbage. If you do the latter, you must keep track of the returned reference in order to properly deallocate it later; if you use the returned value as an intermediate result (as in foo c = a + b + d) you will lose the ability to deallocate the result of b+d, so you'll have permanently trapped some memory. Do this often enough and you'll run out of memory. 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. Good luck, Tony Hodgson ahodgson@hstbme.mit.edu