Topic: operator[]: Should I follow the conventional style?


Author: ittpub!uucp@relay.NL.net
Date: 1995/09/12
Raw View
Distribution:


In article <9509070855.AA06861@slsvhdt.lts.sel.alcatel.de>, kanze
<kanze@lts.sel.alcatel.de> wrote:

> In article <MATT.95Sep6110625@physics2.Berkeley.EDU>
> martelli@cadlab.cadlab.it (Alex Martelli) writes:
>
> |> kanze@gabi-soft.fr (J. Kanze) writes (in comp.lang.c++):
> |> >Wil Evers (wil@ittpub.nl) wrote:

> |> >|>  array[index].doSomethingToIt(args);

> |> >|> Please note that at least some compilers - I'm not sure if
> |> >|> this is standard-conforming - will accept the second syntax
> |> >|> even when we're using the proxy approach. They will call
> |> >|> doSomethingToIt() on the temporary returned by the array's
> |> >|> get() member function and then discard it. In other words,
> |> >|> the array element at index is not changed at all!

> |> in the context of something like (I'm synthesizing from word-level
> |> descriptions by Kanze and Evers):

> |> class A {
> |>      ...
> |> public:
> |>      int doSomethingToIt(int args);
> |> };
>
> |> class proxyA;
>
> |> class arrayA {
> |>     ...
> |> public;
> |>     A& get(int index);
> |>     void put(int index, const A&it);
> |>     proxyA operator[](int index);
> |> };
>
> |> class proxyA {
> |>      arrayA& thearray;
> |>      int theindex;
> |> public:
> |>      proxyA(arrayA& inar, int inin): thearray(inar), theindex(inin) {}
> |>      operator A() { return thearray.get(theindex); }
> |>      void operator=(const A& it) { thearray.put(theindex, it); }
> |> };
>
>
> |> In this case, the behaviour Wil describes is not standard conforming,
> |> I believe; conversions are NOT supposed to be applied to the implicit
> |> "this" operator of any member function, here doSomethingToIt()!
>
> Correct.

[ snip]

I feel I owe an apology to the readers of this newsgroup, in
particular to James and Alex. The compilers I tried (Borland C++ 3.1,
GNU C++ 2.5.8) do *not* accept my original example. I'm sorry! I was
confused because they *do* accept something very similar that bit me a
few times. If we extend the example above by

void f(A& anA) { anA.doSomeThingDoIt(); }

both compilers will accept

main() { arrayA aa(/* args */); f(aa[0]); }

Again, I'm not sure if this is conforming - I think it isn't because a
non-const reference to a temporary is passed to f(). Can someone
please shed some light on this?

- Wil
(wil@ittpub.nl)

---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]