Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!bloom-beacon!apple!claris!hearn From: hearn@claris.com (Bob Hearn) Newsgroups: comp.lang.c++ Subject: Re: Generating temporaries Message-ID: <9431@claris.com> Date: 4 Apr 89 18:53:41 GMT References: <7.UUL1.2#261@persoft.UUCP> Organization: Claris Corporation, Mountain View CA Lines: 59 From article <7.UUL1.2#261@persoft.UUCP>, by ericf@persoft.UUCP (Eric R. Feigenson): > [I'm rather new to C++, so this may be a rather naive query. Please bear > with me] Nope, good question. > I have a class M for which I want to define operator+. My question(s) have > to do with how I generate the temporary that contains the result, and how > such a temporary gets destroyed. > > First, if my operator+ returns an object of class M, it has to create > an object to return. If I understand things right, this will call > operator+, which will return an object of class M (which was > pushed onto the stack), and do a structure copy into c. All the destructors > get called just fine, and no stray memory is left around, but there's the > overhead of the structure copy. > > Now I've also fiddled around with trying to return a reference to an object > M, in order to avoid the structure copy. The code for operator+() has to > allocate a pointer to an object of type M using the "new" operator. > So, if we have some code that looks like: > > M a, b, c; > > // some code to give a and b values > > c = a + b; // calls "M& M::operator+(M& x)" > > and we define operator=(M&) to do the assignment, how can we free the > space allocated by operator+() for the temporary result? If operator=() > does the "delete" then it may destroy some space that we meant to keep > around. Also, in an expression such as "a + b + c", how can the > intermediate temporaries be freed? The destructors get called, but how > can they know to delete the space on the free store? > > To summarize: I want to be able to define operator+ (or any other operator > for that matter) using references (pointers) to avoid the overhead of > structure copy. The problem seems to be knowing when and how to free the > space that the operator must dynamically allocate in order to generate a > result. > > I hope this makes sense. Thanks in advance for your help. Please e-mail > any responses. 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