Xref: utzoo comp.lang.c++:12053 comp.std.c++:692 Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!motcid!stephens From: stephens@motcid.UUCP (Kurt Stephens) Newsgroups: comp.lang.c++,comp.std.c++ Subject: Re: distinguishing operator[] on left and right Message-ID: <6657@celery34.UUCP> Date: 5 Mar 91 16:27:48 GMT References: <1991Feb28.212419.20920@ndl.com> <1991Mar2.000705.3496@mathcs.sjsu.edu> <11634@pasteur.Berkeley.EDU> <1991Mar4.211036.9508@am.dsir.govt.nz> Organization: Motorola Inc., Cellular Infrastructure Div., Arlington Heights, IL Lines: 55 robert@am.dsir.govt.nz (Robert Davies) writes: >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++? How could the compiler tell that the operation won't affect the value of g? the string::operator[]() could be doing just about anything to the privates of g. C++ compliers cannot read minds, or understand the internal semantics of any functions. Example: =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=- #include class X { int i; public: X( int I ) : i(I) {} int operator[](int I) { return i = I; } void print() { printf("%d\n", i ); } }; main() { X a = 1; a.print(); a[-1]; a.print(); } =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= X::operator[](int) means "assign to member i", but because of the association with C's operator[], most container classes limit operator[]() semantics to be "return a lvalue", "return a rvalue" or "lookup in table", which is great because it makes for readable code. Obviously, X::operator[](int) is a bad choice for "assign to member i"; X::operator=(int) would have been much more intuitive handle. But we (and the complier) cannot assume that operator[]() never modifies the state of the class or its instances. Kurt A. Stephens Foo::Foo(){return Foo();} stephens@void.rtsg.mot.com "When in doubt, recurse." -- Kurt A. Stephens Foo::Foo(){return Foo();} stephens@void.rtsg.mot.com "When in doubt, recurse."