Overloading operator []

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Guest's Avatar

    Overloading operator []

    I have not posted to comp.lang.c++ (or comp.lang.c++.m oderated)
    before. In general when I have a C++ question I look for answers in
    "The C++ Programming Language, Third Edition" by Stroustrup.
    However, I've come upon a question that I can neither answer from
    "The Book" or a Google search (so yes, at least I RTFBed). I'm
    hoping that someone in this news group might know the answer.

    Overloading the [] Operator

    Say I want to develop a class that supports the overloaded []
    operator and reads and writes the "int" type. I thought that the
    way this was done was:

    class MyClass
    {
    //...
    // in theory, the RHS operator
    const int operator[](const int i ) const;
    // in theory, the LHS operator
    int& operator[](const int i );
    //...
    }

    Here RHS stands for right-hand-side, or an r-value and LHS stands
    for left-hand-side, or an l-value.

    MyClass foo;

    int i = foo[j]; // RHS reference NOT!
    foo[j] = i; // LHS reference

    Much to my surprise, the first statement "i = foo[j];" seems to
    invoke the overloaded operator I've labeled LHS. I tried this with
    Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
    service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
    for Intel on freeBSD. Both compilers got the same results.

    To put things in more concrete form, I've included a complete test
    code below:

    #include <stdio.h>

    class overloaded
    {
    private:
    int *pArray;

    public:
    overloaded( size_t size )
    {
    pArray = new int[ size ];
    }

    ~overloaded()
    {
    delete [] pArray;
    }

    // in theory, the RHS operator
    const int operator[](const int i ) const
    {
    printf("RHS a[%2d]\n", i );
    return pArray[i];
    }

    // in theory, the LHS operator
    int& operator[](const int i )
    {
    printf("LHS a[%2d]\n", i );
    return pArray[i];
    }
    }; // overloaded


    int
    main()
    {
    const int len = 4;
    overloaded a(len);
    int b[len];

    int i;

    printf("initial izing array...\n");
    for (i = 0; i < len; i++) {
    a[i] = i + 1;
    }

    printf("reading values from array in an 'if' statement...\n" );
    for (i = 0; i < len; i++) {
    if (a[i] != i+1) {
    printf("bad value");
    break;
    }
    }

    printf("reading values from an array in an assignment...\n ");
    for (i = 0; i < len; i++) {
    b[i] = a[i];
    }

    printf("express ion...\n");
    int j = a[1] + a[2];
    return 0;
    }

    When I compile and execute this code I get

    initializing array...
    LHS a[ 0]
    LHS a[ 1]
    LHS a[ 2]
    LHS a[ 3]
    reading values from array in an 'if' statement...
    LHS a[ 0]
    LHS a[ 1]
    LHS a[ 2]
    LHS a[ 3]
    reading values from an array in an assignment...
    LHS a[ 0]
    LHS a[ 1]
    LHS a[ 2]
    LHS a[ 3]
    expression...
    LHS a[ 1]
    LHS a[ 2]

    I expected that the "initialization " would reference the LHS form of
    the overloaded function. However, much to my surprise, the 'if'
    statement and the value reads also referenced the LHS form of the
    overloaded operator. I'm surprised at this, since as far as I can
    tell, this way I've implemented the overloaded [] operators is
    pretty much "text book" approach.

    Is there a way to implement this class so that the RHS [] will be
    called when it seems to be an r-value? That is

    if (a[i] != i+1)
    b[i] = a[i];
    int j = a[1] + a[2];

    In this example the difference is not critical, since the code gets
    the expected results. However, proper invokation of the RHS and LHS
    operators is important in the case of reference counted objects,
    which is the appliction that originally motivated this question.

    I'm working on a third version of a reference counted String class,
    which can be found here:
    http://www.bearcave.com/software/string/index.html. This class
    suffers from a bug caused by the behavior of the [] operator
    described above. In particular, it is making too many copies.

    I have noted Stroustrup's solution using the Cref class (from 11.12
    of "The Book"). However, in his code it appears that you might as
    well omit the RHS version of the [] operator.

    I'd be grateful for a version of the test code above that invokes
    the RHS operator for what appear to be r-value references. Could
    you please copy any postings on this to "iank at bearcave dot com".
    Thank you for your help,

    Ian
    iank at bearcave dot com

    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.m oderated. First time posters: Do this! ]
  • John Harrison

    #2
    Re: Overloading operator []


    "(null)" <iank@idiom.com > wrote in message news:1058054598 .920916@smirk.. .[color=blue]
    > I have not posted to comp.lang.c++ (or comp.lang.c++.m oderated)
    > before. In general when I have a C++ question I look for answers in
    > "The C++ Programming Language, Third Edition" by Stroustrup.
    > However, I've come upon a question that I can neither answer from
    > "The Book" or a Google search (so yes, at least I RTFBed). I'm
    > hoping that someone in this news group might know the answer.
    >
    > Overloading the [] Operator
    >
    > Say I want to develop a class that supports the overloaded []
    > operator and reads and writes the "int" type. I thought that the
    > way this was done was:
    >
    > class MyClass
    > {
    > //...
    > // in theory, the RHS operator
    > const int operator[](const int i ) const;
    > // in theory, the LHS operator
    > int& operator[](const int i );
    > //...[/color]

    I'd prefer

    int operator[](int i ) const;
    int& operator[](int i );

    for an int type the other const's are unecessary.

    Your comments about RHS operator and LHS operator are incorrect however. See
    below.
    [color=blue]
    > }
    >
    > Here RHS stands for right-hand-side, or an r-value and LHS stands
    > for left-hand-side, or an l-value.
    >
    > MyClass foo;
    >
    > int i = foo[j]; // RHS reference NOT!
    > foo[j] = i; // LHS reference
    >
    > Much to my surprise, the first statement "i = foo[j];" seems to
    > invoke the overloaded operator I've labeled LHS. I tried this with
    > Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
    > service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
    > for Intel on freeBSD. Both compilers got the same results.
    >[/color]

    [snip]
    [color=blue]
    >
    > I expected that the "initialization " would reference the LHS form of
    > the overloaded function. However, much to my surprise, the 'if'
    > statement and the value reads also referenced the LHS form of the
    > overloaded operator. I'm surprised at this, since as far as I can
    > tell, this way I've implemented the overloaded [] operators is
    > pretty much "text book" approach.
    >
    > Is there a way to implement this class so that the RHS [] will be
    > called when it seems to be an r-value? That is
    >
    > if (a[i] != i+1)
    > b[i] = a[i];
    > int j = a[1] + a[2];
    >[/color]

    It would be nice if you could do what you want to do but you can't.

    For clarity lets denote operator[] by F, and operator= by G, then
    essentially what you are asking for is the compiler to distinguish between
    calls to F in

    G(...,F(i))

    from

    G(F(i), ...)

    But the compiler cannot do this for any normal function so there is no
    reason to expect it to work for operator[] and operator=.
    [color=blue]
    > In this example the difference is not critical, since the code gets
    > the expected results. However, proper invokation of the RHS and LHS
    > operators is important in the case of reference counted objects,
    > which is the appliction that originally motivated this question.
    >
    > I'm working on a third version of a reference counted String class,
    > which can be found here:
    > http://www.bearcave.com/software/string/index.html. This class
    > suffers from a bug caused by the behavior of the [] operator
    > described above. In particular, it is making too many copies.[/color]

    Right, which is why you should avoid operator[] on reference counted string
    classes. It is impossible to implement in an efficient manner. Implementing
    operator[] on a non-const reference counted string class means a compromise,
    either you have to take a copy of the string immediately even though
    operator[] might only be being used to read from the string, or you have to
    write a proxy class (e.g. Cref in Stroustrup).
    [color=blue]
    >
    > I have noted Stroustrup's solution using the Cref class (from 11.12
    > of "The Book"). However, in his code it appears that you might as
    > well omit the RHS version of the [] operator.[/color]

    Well there is no RHS version of [] you have been misinformed. If you omitted
    the const version of operator[] from Stroustrup's code then the following
    would not compile

    const String x = "abc";
    cout << x[0];

    This is the true meaning of the const version of operator[], it allows you
    to access const objects. Same as any other const method.

    john


    Comment

    • John Harrison

      #3
      Re: Overloading operator []

      >[color=blue]
      > I'm working on a third version of a reference counted String class,
      > which can be found here:
      > http://www.bearcave.com/software/string/index.html. This class
      > suffers from a bug caused by the behavior of the [] operator
      > described above. In particular, it is making too many copies.
      >[/color]

      BTW, from the above site

      "When an STL string object is assigned to another string object, a copy is
      made. In contrast, the String container copies a reference and increments a
      reference count."

      This is not strictly correct, the standard leaves it up to the
      implementation whether to use reference counting or not. My version of the
      STL (dinkumware) does use reference counting.

      john


      Comment

      • Thomas Mang

        #4
        Re: Overloading operator []



        "(null)" schrieb:
        [color=blue]
        > class MyClass
        > {
        > //...
        > // in theory, the RHS operator
        > const int operator[](const int i ) const;
        > // in theory, the LHS operator
        > int& operator[](const int i );
        > //...
        > }[/color]

        All these members are in the private section of the class.
        I assume you missed a "public:" somewhere.



        [color=blue]
        >
        >
        > Here RHS stands for right-hand-side, or an r-value and LHS stands
        > for left-hand-side, or an l-value.
        >
        > MyClass foo;
        >
        > int i = foo[j]; // RHS reference NOT!
        > foo[j] = i; // LHS reference
        >
        > Much to my surprise, the first statement "i = foo[j];" seems to
        > invoke the overloaded operator I've labeled LHS.[/color]

        No surprise at all.
        Your foo-object is non-const, so the compiler invokes the non-const
        overloaded operator[].
        Why should it invoke the const version?

        Things are totally different when foo is defined as const:

        const MyClass foo;

        Then the compiler will, of course, invoke the const-version of operator[].


        Note that this overload resolution has nothing to do with the fact if you
        use your overloaded operator[] at the call site as LHS or RHS.


        regards,

        Thomas

        [ See http://www.gotw.ca/resources/clcm.htm for info about ]
        [ comp.lang.c++.m oderated. First time posters: Do this! ]

        Comment

        • Joshua Lehrer

          #5
          Re: Overloading operator []

          "John Harrison" <john_andronicu s@hotmail.com> wrote in message news:<berg4s$89 2s3$1@ID-196037.news.uni-berlin.de>...
          [color=blue]
          > Right, which is why you should avoid operator[] on reference counted string
          > classes. It is impossible to implement in an efficient manner. Implementing
          > operator[] on a non-const reference counted string class means a compromise,
          > either you have to take a copy of the string immediately even though
          > operator[] might only be being used to read from the string, or you have to
          > write a proxy class (e.g. Cref in Stroustrup).[/color]


          You seem to be making an assumption here. If I read your statement
          correctly, you say that it is impossible to implement the non-const
          index operator on a reference counted String in an efficient manner.
          You then state that in order to do this, you need to write a proxy
          class. Therefore, you are making the assumption that the proxy class
          makes the class non-efficient.

          This *may* not be true. It depends on if the compiler can optimize
          away much, if not all, of the use of the proxy class.

          Even if this one function makes the refernce counted String class
          slightly less efficient to use, the other gains from the
          refernce-counted String class *may* outweigh this small expense- it
          proveably did on our system. The only way to tell on your system is
          to try it.

          We have a home grown reference counted String class, and it uses a
          proxy class to implement the return value of the non-const index
          operator. The class is extremely efficient, and fast. Our source
          code base which uses this class has about 400 engineering-man-years of
          development in it, consisting of hundreds of thousands of lines of
          code. When we released our reference counted String class in place of
          the old version, we saw at least a 10% improvement in our average CPU
          consumption. Sections of our application which used Strings heavily
          saw much more significant gains. We are certain that we would see
          even more gains if we did not have legacy code that depended on
          certain behaviors of the old String class, which required some slight
          inefficiencies be purposely introduced into the new String class.

          The bottom line- lots of reference-counted string bashing goes on in
          this newsgroup. Most of this bashing is by people who probably never
          wrote such a class themselves. We took the time to write one, and
          thoroughly test and review it for completeness, correctness, and
          safety. This class has had nothing but positive impact on *our*
          system. Your mileage may vary.

          joshua lehrer
          factset research systems
          NYSE:FDS

          p.s. to order your very own "RefStrings Rule!" bumper-sticker, send a
          self addressed stamped envelope to...

          Comment

          • John Harrison

            #6
            Re: Overloading operator []


            "Joshua Lehrer" <usenet_cpp@leh rerfamily.com> wrote in message
            news:31c49f0d.0 307132005.6b922 8e3@posting.goo gle.com...[color=blue]
            > "John Harrison" <john_andronicu s@hotmail.com> wrote in message[/color]
            news:<berg4s$89 2s3$1@ID-196037.news.uni-berlin.de>...[color=blue]
            >[color=green]
            > > Right, which is why you should avoid operator[] on reference counted[/color][/color]
            string[color=blue][color=green]
            > > classes. It is impossible to implement in an efficient manner.[/color][/color]
            Implementing[color=blue][color=green]
            > > operator[] on a non-const reference counted string class means a[/color][/color]
            compromise,[color=blue][color=green]
            > > either you have to take a copy of the string immediately even though
            > > operator[] might only be being used to read from the string, or you have[/color][/color]
            to[color=blue][color=green]
            > > write a proxy class (e.g. Cref in Stroustrup).[/color]
            >
            >
            > You seem to be making an assumption here. If I read your statement
            > correctly, you say that it is impossible to implement the non-const
            > index operator on a reference counted String in an efficient manner.
            > You then state that in order to do this, you need to write a proxy
            > class. Therefore, you are making the assumption that the proxy class
            > makes the class non-efficient.[/color]

            OK, maybe I didn't choose the best words. Substitute 'as simply as you
            think' for 'efficiently'.
            [color=blue]
            >
            > This *may* not be true. It depends on if the compiler can optimize
            > away much, if not all, of the use of the proxy class.
            >
            > Even if this one function makes the refernce counted String class
            > slightly less efficient to use, the other gains from the
            > refernce-counted String class *may* outweigh this small expense- it
            > proveably did on our system. The only way to tell on your system is
            > to try it.[/color]

            Couldn't disagree with that.
            [color=blue]
            >
            > We have a home grown reference counted String class, and it uses a
            > proxy class to implement the return value of the non-const index
            > operator. The class is extremely efficient, and fast. Our source
            > code base which uses this class has about 400 engineering-man-years of
            > development in it, consisting of hundreds of thousands of lines of
            > code. When we released our reference counted String class in place of
            > the old version, we saw at least a 10% improvement in our average CPU
            > consumption. Sections of our application which used Strings heavily
            > saw much more significant gains. We are certain that we would see
            > even more gains if we did not have legacy code that depended on
            > certain behaviors of the old String class, which required some slight
            > inefficiencies be purposely introduced into the new String class.
            >
            > The bottom line- lots of reference-counted string bashing goes on in
            > this newsgroup.[/color]

            Not by me (at least not intentionally). Hell, I even believe that copy on
            write is a generally useful technique.
            [color=blue]
            > Most of this bashing is by people who probably never
            > wrote such a class themselves. We took the time to write one, and
            > thoroughly test and review it for completeness, correctness, and
            > safety. This class has had nothing but positive impact on *our*
            > system. Your mileage may vary.
            >
            > joshua lehrer
            > factset research systems
            > NYSE:FDS
            >
            > p.s. to order your very own "RefStrings Rule!" bumper-sticker, send a
            > self addressed stamped envelope to...[/color]

            Where? Where can I get one!?

            john


            Comment

            • llewelly

              #7
              Re: Overloading operator []

              iank@idiom.com ((null)) writes:
              [color=blue]
              > I have not posted to comp.lang.c++ (or comp.lang.c++.m oderated)
              > before. In general when I have a C++ question I look for answers in
              > "The C++ Programming Language, Third Edition" by Stroustrup.
              > However, I've come upon a question that I can neither answer from
              > "The Book" or a Google search (so yes, at least I RTFBed).[/color]

              Well it is a big book sometimes people miss things, or don't add up
              seperate things in the intended way. 10.2.6 explains constant
              member functions.
              [color=blue]
              >
              > I'm hoping that someone in this news group might know the answer.
              >
              > Overloading the [] Operator
              >
              > Say I want to develop a class that supports the overloaded []
              > operator and reads and writes the "int" type. I thought that the
              > way this was done was:
              >
              > class MyClass
              > {
              > //...
              > // in theory, the RHS operator
              > const int operator[](const int i ) const;
              > // in theory, the LHS operator
              > int& operator[](const int i );[/color]

              'const' is a propertery of an object, not of an operator=. If the
              instance of MyClass is const, the first will be called, and if the
              instance of MyClass is not const, the second will be called. This
              is true regardless of which side of operator= the use of
              operator[] occurs.

              (Note: in order to have behavior more like that of builtin[], the
              first operator[] should return 'int const&' )
              [color=blue]
              > //...
              > }
              >
              > Here RHS stands for right-hand-side, or an r-value and LHS stands
              > for left-hand-side, or an l-value.
              >
              > MyClass foo;
              >
              > int i = foo[j]; // RHS reference NOT!
              > foo[j] = i; // LHS reference
              >
              > Much to my surprise, the first statement "i = foo[j];" seems to
              > invoke the overloaded operator I've labeled LHS.[/color]
              [snip]

              This is correct behavior; foo is not const, so
              int& MyClass::operat or[](int) is called, and not
              int const MyClass::operat or[](int) const . It is constness,
              and not side of operator=, that matters. Had you written:

              MyClass const foo;

              int i = foo[j];
              foo[j]= i;

              both calls would have called
              int const MyClass::operat or[](int) const .

              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
              [ comp.lang.c++.m oderated. First time posters: Do this! ]

              Comment

              • kanze@gabi-soft.fr

                #8
                Re: Overloading operator []

                usenet_cpp@lehr erfamily.com (Joshua Lehrer) wrote in message
                news:<31c49f0d. 0307132005.6b92 28e3@posting.go ogle.com>...

                [...][color=blue]
                > The bottom line- lots of reference-counted string bashing goes on in
                > this newsgroup. Most of this bashing is by people who probably never
                > wrote such a class themselves. We took the time to write one, and
                > thoroughly test and review it for completeness, correctness, and
                > safety. This class has had nothing but positive impact on *our*
                > system. Your mileage may vary.[/color]

                I suspect that most of the bashing is an accidental extension of
                reference-count bashing with regards to an implementation of
                std::string. The standard does NOT allow the use of a proxy -- the
                non-const version of operator[] must return a real reference. This
                requires special handling even in a single threaded version with
                reference counting, and is almost impossible to get right efficiently in
                a multi-threaded version -- you end up needing a lock for practically
                every single access.

                For the rest, in the past, I too have found reference counting to be a
                win. In my own code -- I can't speak for others. (Like you, my string
                class used a proxy as the return value for the non-const operator[].)

                --
                James Kanze GABI Software mailto:kanze@ga bi-soft.fr
                Conseils en informatique orientée objet/ http://www.gabi-soft.fr
                Beratung in objektorientier ter Datenverarbeitu ng
                11 rue de Rambouillet, 78460 Chevreuse, France, +33 (0)1 30 23 45 16

                Comment

                • Carl Barron

                  #9
                  Re: Overloading operator []

                  (null) <iank@idiom.com > wrote:
                  [color=blue]
                  > I have not posted to comp.lang.c++ (or comp.lang.c++.m oderated)
                  > before. In general when I have a C++ question I look for answers in
                  > "The C++ Programming Language, Third Edition" by Stroustrup.
                  > However, I've come upon a question that I can neither answer from
                  > "The Book" or a Google search (so yes, at least I RTFBed). I'm
                  > hoping that someone in this news group might know the answer.
                  >
                  > Overloading the [] Operator
                  >
                  > Say I want to develop a class that supports the overloaded []
                  > operator and reads and writes the "int" type. I thought that the
                  > way this was done was:
                  >
                  > class MyClass
                  > {
                  > //...
                  > // in theory, the RHS operator
                  > const int operator[](const int i ) const;
                  > // in theory, the LHS operator
                  > int& operator[](const int i );
                  > //...
                  > }
                  >
                  > Here RHS stands for right-hand-side, or an r-value and LHS stands
                  > for left-hand-side, or an l-value.
                  >
                  > MyClass foo;
                  >
                  > int i = foo[j]; // RHS reference NOT!
                  > foo[j] = i; // LHS reference
                  >
                  > Much to my surprise, the first statement "i = foo[j];" seems to
                  > invoke the overloaded operator I've labeled LHS. I tried this with
                  > Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
                  > service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
                  > for Intel on freeBSD. Both compilers got the same results.
                  >
                  > To put things in more concrete form, I've included a complete test
                  > code below:
                  >
                  > #include <stdio.h>
                  >
                  > class overloaded
                  > {
                  > private:
                  > int *pArray;[/color]
                  const int rhs_bracket(i) const
                  {
                  // perform = overloaded_arra y[i]
                  printf("RHS a[%2d]\n",i);
                  return pArray[i[;
                  }
                  void lhs_bracket(int i,int x)
                  {
                  // perform overloaded_arra y[i] = x;
                  printf("LHS a[%2d] = %d\n",i,x);
                  pArray[i] = x;
                  }
                  [color=blue]
                  > public:[/color]
                  class proxy
                  {
                  overloaed *over;
                  int index;
                  proxy(overloade d *a,int b):over(a),inde x(b){}
                  public:
                  friend class overloaded;
                  operator int() { return over->rhs_bracket(i) ;}
                  proxy & operator = (int x)
                  {
                  over->lhs_bracket(i, x);
                  return *this;
                  }
                  };
                  friend class proxy;
                  proxy operator [] (int i) {return proxy(this,i);}
                  [color=blue]
                  > overloaded( size_t size )
                  > {
                  > pArray = new int[ size ];
                  > }
                  >
                  > ~overloaded()
                  > {
                  > delete [] pArray;
                  > }
                  >[/color]
                  #if 0[color=blue]
                  > // in theory, the RHS operator
                  > const int operator[](const int i ) const
                  > {
                  > printf("RHS a[%2d]\n", i );
                  > return pArray[i];
                  > }
                  >
                  > // in theory, the LHS operator
                  > int& operator[](const int i )
                  > {
                  > printf("LHS a[%2d]\n", i );
                  > return pArray[i];
                  > }[/color]
                  #endif
                  [color=blue]
                  > }; // overloaded
                  > ...[/color]
                  This will result in different behavior depending on whether operator
                  [] is used to read or write data to/from an overloaded.

                  Note i used mutual friendship so only overloaded::ope rator [] will
                  create an overloaded::pro xy objwct. and private functions to do the
                  different items on the lhs and rhs of an equal sign. Making them private
                  and proxy a friend means that only proxy is going to access these
                  implimentation detail functions. This approach can also be used with
                  operator *() and operator ->() to preform different operations when
                  reading and writing.

                  [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                  [ comp.lang.c++.m oderated. First time posters: Do this! ]

                  Comment

                  • Thomas Mang

                    #10
                    Re: Overloading operator []



                    James Kanze schrieb:
                    [color=blue]
                    >
                    > Normally, this should not be a problem. There are exceptions,
                    > however, when you need to do something different if the target is
                    > actually modified. In such cases, you typically need to use some sort
                    > of Proxy, e.g.:
                    >
                    > class MyClass
                    > {
                    > public:
                    > class Proxy
                    > {
                    > friend class MyClass ;
                    > public:
                    > operator int() const
                    > {
                    > return myOwner.get( myIndex ) ;
                    > }
                    > Proxy const& operator=( int other ) const
                    > {
                    > myOwner.put( myIndex, other ) ;
                    > return *this ;
                    > }
                    > private:
                    > Proxy( MyClass& owner, int index )
                    > : myOwner( owner )
                    > , myIndex( index )
                    > {
                    > }
                    >
                    > MyClass& myOwner ;
                    > int myIndex ;
                    > } ;
                    >
                    > void put( int index, int newValue ) ;
                    > int get( int index ) const ;
                    >
                    > Proxy operator[]( int index )
                    > {
                    > return Proxy( *this, index ) ;
                    > }
                    > int operator[]( int index ) const
                    > {
                    > return get( index ) ;
                    > }
                    > } ;
                    >
                    > All of the actual logic is then in get and put.[/color]

                    What advantage does one gain by writing a proxy class, instead of simply
                    returning an int&?

                    That is, why not simply write the following overloaded operator[]?

                    int& operator[](int index)


                    regards,

                    Thomas


                    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                    [ comp.lang.c++.m oderated. First time posters: Do this! ]

                    Comment

                    • Glen Low

                      #11
                      Re: Overloading operator []

                      > Much to my surprise, the first statement "i = foo[j];" seems to[color=blue]
                      > invoke the overloaded operator I've labeled LHS. I tried this with
                      > Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
                      > service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
                      > for Intel on freeBSD. Both compilers got the same results.[/color]

                      What you need is to return a proxy class that overloads operator= and
                      operator int. Roughly:

                      class MyClass
                      {
                      public:
                      int operator[] (int i) const; // RHS
                      int_proxy operator[] (int i) { return int_proxy (p_ + i); }
                      private:
                      int *p_;
                      };

                      class int_proxy
                      {
                      public:
                      int_proxy& operator= (int val) { *r_ = val; }
                      operator int () const; // RHS
                      int_proxy (int* r): r_ (r) { }
                      private:
                      int *r_;
                      };

                      Essentially the int_proxy acts like a int&, but whatever special code
                      you would have put in the RHS function in the original, you put that
                      same code in the RHS function in the proxy. (Stylistically, you could
                      use templates and put int_proxy inside of MyClass.) I believe
                      std::vector<boo l> is specialized to do this.

                      Now when you call a [i], you get a temporary proxy. If there is an
                      access, then operator int gets called with your special RHS code; if
                      there is a mutate, then operator= gets called.

                      If it's all inline and optimizations are on, chances are the compiler
                      will optimize away the temporary int_proxy object. The only drawback I
                      can see is that the return type is no longer int&, which may crap out
                      code that expects it e.g. int& ri = a [i].

                      P.S. If you're irritated by having to repeat RHS code twice, either
                      cause the int_proxy version to call the MyClass version, or return a
                      const int_proxy from the MyClass RHS function.

                      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                      [ comp.lang.c++.m oderated. First time posters: Do this! ]

                      Comment

                      • Rob

                        #12
                        Re: Overloading operator []


                        "(null)" <iank@idiom.com > wrote in message news:1058054598 .920916@smirk.. .
                        [Snip][color=blue]
                        >
                        > class MyClass
                        > {
                        > //...
                        > // in theory, the RHS operator
                        > const int operator[](const int i ) const;
                        > // in theory, the LHS operator
                        > int& operator[](const int i );
                        > //...
                        > }
                        >
                        > Here RHS stands for right-hand-side, or an r-value and LHS stands
                        > for left-hand-side, or an l-value.
                        >
                        > MyClass foo;
                        >
                        > int i = foo[j]; // RHS reference NOT!
                        > foo[j] = i; // LHS reference
                        >
                        > Much to my surprise, the first statement "i = foo[j];" seems to
                        > invoke the overloaded operator I've labeled LHS. I tried this with
                        > Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
                        > service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
                        > for Intel on freeBSD. Both compilers got the same results.
                        >[/color]
                        [Snip]

                        This is actually the way it's supposed to be. foo is not a const object,
                        so when
                        there is a choice (as in this case) the non-const version of the operator
                        should
                        be invoked.




                        [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                        [ comp.lang.c++.m oderated. First time posters: Do this! ]

                        Comment

                        • Siemel Naran

                          #13
                          Re: Overloading operator []

                          "Francis Glassborow" <francis.glassb orow@ntlworld.c om> wrote in message
                          [color=blue]
                          > class hue{
                          > public:
                          > bool operator[](int bit)const {
                          > if(bit <0 or bit >7) return false;
                          > return bitset<8>(code_ )[bit];
                          > }
                          > class ref;
                          > friend class hue::ref;
                          > class ref{
                          > public:
                          > ref(hue & h, int n):h_(h),bit(n) {};
                          > operator bool(){
                          > if (bit <0 or bit >7) return false;
                          > return bitset<8>(h_)[bit];
                          > }
                          > void operator=(bool val){
                          > if(bit <0 or bit >7) return;
                          > bitset<8> v(h_);
                          > v[bit] = val;
                          > h_ = (unsigned char)v.to_ulong ();
                          > }
                          > private:
                          > hue & h_;
                          > int bit;
                          > };
                          > ref operator[](int bit){return ref(*this, bit);}[/color]

                          How do you deal with the problem of replicating the interface of class bool
                          in class hue::ref? No problem with class bool as you only have to worry
                          about operator= as you did above (and I did in my example). But what about
                          other member functions like operator+=, memfun(), etc?

                          --
                          +++++++++++
                          Siemel Naran


                          [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                          [ comp.lang.c++.m oderated. First time posters: Do this! ]

                          Comment

                          • Glen Low

                            #14
                            Re: Overloading operator []

                            > That is, why not simply write the following overloaded operator[]?[color=blue]
                            >
                            > int& operator[](int index)[/color]

                            An int& is dumb, it cannot distinguish whether it is being written to
                            or read. A proxy object is smart, it knows when it is written (via
                            operator=) or read (via operator int), and can execute different code
                            as a result.

                            [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                            [ comp.lang.c++.m oderated. First time posters: Do this! ]

                            Comment

                            • Francis Glassborow

                              #15
                              Re: Overloading operator []

                              In message <iGLRa.61254$3o 3.4015423@bgtns c05-news.ops.worldn et.att.net>,
                              Siemel Naran <SiemelNaran@RE MOVE.att.net> writes[color=blue]
                              >How do you deal with the problem of replicating the interface of class bool
                              >in class hue::ref? No problem with class bool as you only have to worry
                              >about operator= as you did above (and I did in my example). But what about
                              >other member functions like operator+=, memfun(), etc?[/color]

                              Sorry, I am totally confused. bool is a fundamental type and not a
                              class. Operator bool 'returns' a bool by value.

                              --
                              ACCU Spring Conference 2003 April 2-5
                              The Conference you should not have missed
                              ACCU Spring Conference 2004 Late April
                              Francis Glassborow ACCU



                              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                              [ comp.lang.c++.m oderated. First time posters: Do this! ]

                              Comment

                              Working...