Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!mailrus!purdue!bu-cs!bloom-beacon!apple!kanner From: kanner@Apple.COM (Herbert Kanner) Newsgroups: comp.lang.c++ Subject: Re: use of new allocator with reference variables Keywords: c++, new, reference Message-ID: <16124@apple.Apple.COM> Date: 26 Aug 88 01:44:09 GMT References: <646@paris.ICS.UCI.EDU> Reply-To: kanner@apple.com.UUCP (Herbert Kanner) Distribution: na Organization: Development Systems Group, Apple Computer Lines: 47 In article <646@paris.ICS.UCI.EDU> schmidt@bonnie.ics.uci.edu (Douglas C. Schmidt) writes: >Hi, > > I've been browsing through Stroustrup's C++ book and came >across the following puzzling construct on page 34: > >Vec& sum = *new Vec(s); > >I don't believe that this use of the new allocator (preceded by the >'*') is described anywhere else in the book. Could someone please >explain the meaning of this, in the context of the function >depicted below? > >Vec operator+(Vec a, Vec b) { > int s = a.size(); > if (s != b.size()) error("foo"); > Vec& sum = *new Vec(s); > int *sp = sum.v; > int *ap = a.v; > int *bp = b.v; > while (s--) *sp++ = *ap++ + *bp++; > return sum; >} > It is probably impossible to give a short explanation that will be understandable. If my explanation makes no sense to you, study section 3.2.6 on the "new" operator and section 2.3.10 on references. Also, I suggest you simply not worry about anything that is not understood in chapter 1 until you have read the rest of the book three times. Having said that: Vec& sum = *new Vec(s); is explained as follows. sum is declared as a reference to Vec--that is what Vec& is. The assigment is an initialization. Initialization of a reference to Vec must by assigning a Vec. The "new" operator returns a pointer to the requested type, namely a pointer to Vec. The "*" dereferences this pointer, yielding the Vec that is required. Herb Kanner Apple Computer, Inc. {idi, ios, nsc}!apple!kanner kanner@apple.apple.com