Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!mcsun!ukc!icdoc!sot-ecs!sra From: sra@ecs.soton.ac.uk (Stephen Adams) Newsgroups: comp.lang.c++ Subject: Re: Read-only data access Message-ID: Date: 14 Jun 91 16:03:32 GMT References: <1654@balrog.ctron.com> <1991Jun13.211926.20276@lynx.CS.ORST.EDU> Sender: news@ecs.soton.ac.uk Organization: Southampton University Computer Science Lines: 66 In-reply-to: budd@fog.CS.ORST.EDU's message of 13 Jun 91 21:19:26 GMT In article <1654@balrog.ctron.com> bangrazi@ctron.com writes: [A neat trick using references to give parenthesis free access to controlled member] In article <1991Jun13.211926.20276@lynx.CS.ORST.EDU> budd@fog.CS.ORST.EDU (Tim Budd) writes: > This is a neat trick. I like it. But I think some of the details are > wrong (at least they don't work as planned using GNU 1.37). The declaration > needs to be int& const (reference to a constant), not const int & (constant > reference). Also G++ doesn't like the constant assignment as shown, but > will allow me to put it in the constructor. > > Here is the example fixed up (at least it works on MY machine). > > class Z { > public: > int& const z; > Z() : z(zP) { zP = 12; } > > modifier() { /* methods can modify zP */ zP += 7; } > private: > int zP; > }; > At first I thought that it was a nice idea. Now I am not so sure. There are problems: 1. The copy constructor must also initialize z in this way (easily forgotten). If it does not, z in the copy will refer to zP in the original object. It might take a lifetime to figure out a bug like that. 2. An assignment operator is equally tricky: it can't be the bitwise for the same reasons as (1). Assignment has to copy everything else by hand. (The destination object has already had the references set up by its constructor.) 3. For various reasons like the above, in the general case the reference has to be stored as a pointer. In this example this doubles the size of the object (so might halve the speed of the program). In view of these disappointments I think that I will stick with the `.z()' syntax. I am used to parentheses - I used to be a lisp programmer :-) A revised definition is: class Z { public: int& const z; Z() : z(zP) { zP = 12; } Z(Z& other) : z(zP) { zP=other.zP; } void operator = (Z& other) { zP=other.zP; } modifier() { /* methods can modify zP */ zP += 7; } private: int zP; }; -- Stephen Adams S.R.Adams@ecs.soton.ac.uk Computer Science University of Southampton Southampton SO9 5NH, UK