Path: utzoo!dptcdc!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!uunet!mcvax!ukc!axion!stc!root44!hrc63!pj From: pj@hrc63.co.uk (Mr P Johnson "Baddow") Newsgroups: comp.lang.c++ Subject: Re: Generating temporaries Summary: Arrggggh Message-ID: <567@hrc63.co.uk> Date: 17 Apr 89 12:15:43 GMT References: <7.UUL1.2#261@persoft.UUCP> <9431@claris.com> Organization: GEC Hirst Research Centre, Wembley, England. Lines: 49 In article <9431@claris.com>, hearn@claris.com (Bob Hearn) writes: > I think this is a good question whose answer should be posted rather than > just emailed. > > One thing you can do is have operator+ have a static local object of class > M that it puts the result into. You can return a reference to this, and > after you do the copy > > a = b + c > > to a from the temp the temp is not referenced anymore, so it is free to be > used again whenever it is needed. You don't have to use new or delete, > and in fact the storage for the temp never has to get thrown away. > > Bob Hearn > hearn@claris.com What happens when you do something like a = (b + c) + d; C++ calls "operator+(b, c). This puts the result in your internal static & returns a reference. This reference then goes into the outer addition, which (without realising it) will overwrite its argument with its result. I know how you feel: the way C++ does this is not very efficient. It would be nice if operators could be told where to put their results. My only solution is to suggest providing a "+=" operator. This would add to its first argument and then return a reference to that argument. Much better. It might be possible to pull some trick with the "M::M( M& )" constructor to avoid this: if you define this constructor then it will get called for function argument/return values instead of the default bit-copy function, but you do have to be careful how this affects your other functions. This constructor is explained in Stroustrup section 6.6. Also, remember that "=" can be defined, otherwise it is also a bit-copy. Some compilers are intelligent and avoid doing two bit-copies. Paul BTW, I am not an expert, so this could be wrong. If this has been dealt with, sorry. We have problems with our mail feed right now.