Xref: utzoo comp.lang.c++:12124 comp.std.c++:713 Path: utzoo!news-server.csri.toronto.edu!rutgers!usc!samsung!uunet!pdn!tscs!tct!chip From: chip@tct.uucp (Chip Salzenberg) Newsgroups: comp.lang.c++,comp.std.c++ Subject: Re: distinguishing operator[] on left and right Message-ID: <27D7F747.39E@tct.uucp> Date: 8 Mar 91 20:42:46 GMT References: <1991Mar2.000705.3496@mathcs.sjsu.edu> <1991Mar2.212017.13885@world.std.com> <1991Mar7.062634.7598@am.dsir.govt.nz> Organization: Teltronics/TCT, Sarasota, FL Lines: 36 According to robert@am.dsir.govt.nz (Robert Davies): >I suggested having two versions of the operator[] > char &operator[](int i) > char operator[](int i) const I've done this. > char c = ((const String)g)[3]; Perhaps you meant char c = ((const String &)g)[3]; That's less likely to create a temporary. >I suggest that it would 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. There's the rub. How's the compiler supposed to know that? We may know from reading the class definition what's meant, but the compiler hasn't got a prayer at figuring out when to call the const function even though you're not operating on a const object. A workaround would be to create a const reference to the object in question, and use it for access: String s; String &r = s; char c = s[0]; // slow char d = r[0]; // fast -- Chip Salzenberg at Teltronics/TCT , "Most of my code is written by myself. That is why so little gets done." -- Herman "HLLs will never fly" Rubin