Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!yale.edu!ox.com!umich!vela!schemers From: schemers@vela.acs.oakland.edu (Roland Schemers III) Newsgroups: comp.lang.c++ Subject: Re: How are strings efficiently concatenated? Summary: StringTmp Message-ID: <7289@vela.acs.oakland.edu> Date: 16 Jun 91 11:18:52 GMT References: <2825@umriscc.isc.umr.edu> Organization: Oakland University, Rochester MI. Lines: 36 In article <2825@umriscc.isc.umr.edu> jamesh@cs.umr.edu (James Hartley) writes: > >How is one to reclaim heapspace when concatenating strings together as in: > > string s2("two"); > s0 = s1 + s2; > >The expression s1 + s2 will allocate space for "onetwo", but s0 will create >a new copy "onetwo". How is the intermediate string deallocated? What I >would really like to do is write efficient code for the following -- > > s0 = s1 + s2 + s3; The way I have seen to do it is creating another string type called StringTmp for example, and have + return a StringTmp. The first 's1+s2' returns a StringTmp which is then added to s3. Since you return a StringTmp you can write StringTmp &operator+(StringTmp &,String &) so that it just appends the String. Then the assignment to s0 just involves changing s0 to point to the StringTmp and at the same time null out the pointer in the StringTmp so it does not get deallocated by the destructor. This can be done through the function String &operator = (StringTmp &). If I ever get time I was planning on adding StringTmp's back to my String class. I took them out because of all the extra functions they were adding and I was trying to keep the class to a minimum. Another suggestion for the StringTmp class might be to have it initially allocate more space then a normal String, since it might be more likely to grow. My String class has a static variable called hunksize which is the size the String will grow when it is expanded. Roland -- Roland J. Schemers III Systems/Network Manager schemers@vela.acs.oakland.edu (Ultrix) Oakland University schemers@argo.acs.oakland.edu (VMS) Rochester, MI 48309-4401 OU in Michigan! Say it slow: M-i-c-h-i-g-a-n (313)-370-4323