Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wasatch!gr.utah.edu!mecklen From: mecklen%gr.utah.edu@wasatch.utah.edu (Robert Mecklenburg) Newsgroups: comp.lang.c++ Subject: Re: Generating temporaries Message-ID: <1531@wasatch.utah.edu> Date: 5 Apr 89 14:48:50 GMT References: <7.UUL1.2#261@persoft.UUCP> Sender: news@wasatch.utah.edu Reply-To: mecklen%gr.utah.edu.UUCP@wasatch.utah.edu (Robert Mecklenburg) Organization: University of Utah CS Dept Lines: 56 >In article <7.UUL1.2#261@persoft.UUCP> ericf@persoft.UUCP (Eric R. Feigenson) writes: > > [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. We have a points package (xyz coordinates) which I have just converted to use '+', '-', and '*' operators. The basic method I used for generating temporaries was to allocate a permanent pool of points and treat it as a circular list. Points are declared as struct point_type { real_type xyz[3]; point_type &operator+( point_type &p ); }; And the pool looks like extern const int MAX_POINT_POOL; extern point_type point_pool[]; extern point_type *pt_ptr; When I need another temporary I call the allocation function inline point_type * pt_nextpt() { if ( ++pt_ptr >= &point_pool[MAX_POINT_POOL] ) pt_ptr = point_pool; return pt_ptr; } So the following code allocates two temporaries and performs one structure copy at the end point_type p; p = a + b + c; The advantages of this are: 1. easy to implement and understand 2. efficient (overhead of an increment and test-and-branch) The disadvantages are: 1. breaks easily if programmer holds on to a temporary too long, the circular queue will eventually trash his temporary with no warning; 2. to be reasonably safe the pool must be reasonably large (we use MAX_POINT_POOL = 64). Comments? Robert Mecklenburg