Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!shadooby!accuvax.nwu.edu!tank!uwvax!persoft!ericf From: ericf@persoft.UUCP (Eric R. Feigenson) Newsgroups: comp.lang.c++ Subject: Generating temporaries Message-ID: <7.UUL1.2#261@persoft.UUCP> Date: 4 Apr 89 14:10:37 GMT Organization: Persoft, Inc. Lines: 49 [I'm rather new to C++, so this may be a rather naive query. Please bear with me] 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. -Eric --------------------------------------------------------------------------- -Eric Feigenson Persoft, Inc. (Internet) ericf@Persoft.COM (UUCP) {ihnp4, seismo, uunet, allegra}!uwvax!persoft!ericf