Xref: utzoo comp.lang.c++:12011 comp.std.c++:677 Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!comp.vuw.ac.nz!am.dsir.govt.nz!robert From: robert@am.dsir.govt.nz (Robert Davies) Newsgroups: comp.lang.c++,comp.std.c++ Subject: Re: distinguishing operator[] on left and right Message-ID: <1991Mar4.211036.9508@am.dsir.govt.nz> Date: 4 Mar 91 21:10:36 GMT References: <1991Feb28.212419.20920@ndl.com> <1991Mar2.000705.3496@mathcs.sjsu.edu> <11634@pasteur.Berkeley.EDU> Organization: DSIR Applied Mathematics, Wellington, NZ Lines: 53 re: distinguishing operator[] on the left and right. This follows up Greg Gilley's item. I think C++ could be improved here. The "right" way of distinguishing the access to g in char c = g[3]; and g[3] = c; would be with "const". You need two versions of the subscript function (my examples are based on Tony Hansen's string class): char &operator[](int i) { if (p->refcount > 1) disconnect(); return str()[i]; } char operator[](int i) const { return str()[i]; } Currently (in Turbo C++ or Glockenspiel C++; my version of Zortech can't distinguish between the 2 versions) you need to write char c = ((const string)g)[3]; to get the second version. Which is a bit messy. But wouldn't it be reasonable for the second version to be the default if the compiler can tell that the operation won't affect the value of g? Was this kind of issue raised in the recent discussion on const in comp.std.c++? I don't think Joe Buck's solution using an extra class is fully satisfactory as it uses up the one coercion that C++ allows. For example, in his example, double d = v[4]; will not work. Finally, do we really need delayed copy - or does it just cause more trouble than it is worth? The only place it might be necessary is in returning values from a function. And someone suggested that under some circumstances a clever compiler could avoid the copy you would ordinarily expect in a return. Robert