Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!usc!brutus.cs.uiuc.edu!zaphod.mps.ohio-state.edu!sunybcs!oswego!news From: dl@g.g.oswego.edu (Doug Lea) Newsgroups: comp.lang.c++ Subject: Re: operator []: ref vs value Message-ID: Date: 25 Feb 90 15:01:04 GMT References: <5216@brazos.Rice.edu> <25E5841D.5B4A@tct.uucp> Sender: news@oswego.Oswego.EDU (Network News) Reply-To: dl@oswego.edu Organization: SUNY Oswego Lines: 43 In-reply-to: chip@tct.uucp's message of 23 Feb 90 18:42:36 GMT > From: chip@tct.uucp (Chip Salzenberg): > > According to dougm@zamenhof.rice.edu (Doug Moore): > >Unfortunately, I want one behavior when the pseudo-array access occurs > >as an rvalue and another when it appears as an lvalue. Can I get what > >I want? > > You almost had it. Define a reference_to_missing_array_element type, > and have operator[] return an object of that type. Then define: > > reference_to_missing_array_element::operator float() > > return 0.0 > > reference_to_missing_array_element::operator = (float) > > create the missing array element and assign to it > > No sweat. > Consider what happens in void inc(float& f) { f += 1.0; } main() { // ... inc(v[0]); } Here, v[0] returns a reference_to_missing_array_element, which is `coerced' to return a constant value (0.0). The 0.0 is made into a temporary variable in order to make a reference. This temporary is then modified in inc(), without touching the underlying representation in v. This is probably not what a user would have in mind. -Doug -- Doug Lea, Computer Science Dept., SUNY Oswego, Oswego, NY, 13126 (315)341-2367 email: dl@oswego.edu or dl%oswego.edu@nisc.nyser.net UUCP :...cornell!devvax!oswego!dl or ...rutgers!sunybcs!oswego!dl