opStar

Janice Caron caron800 at googlemail.com
Sun Nov 11 23:21:24 PST 2007


On Nov 12, 2007 2:19 AM, Walter Bright <newshound1 at digitalmars.com> wrote:
> Adding new properties is a pretty disruptive thing to do, especially
> common names.

I agree. If you were going to introduce a new property, I'd be the
/first/ to argue that it shouldn't be called something as common as
"value". There are plenty of less common alternatives.

But that said, it wouldn't be my first choice. My first choice would
be to have the dot operator automatically call opDeref as many times
as necessary, so that iterators behave like pointers.

The reason for all this fuss is that the status quo is not perfect.
Suppose I want to implement an iterator which iterates over very large
structs. Like this:

    struct VeryLargeStruct
    {
        int m;
        /* Lots of other stuff */
    }

    struct Iterator
    {
        VeryLargeStruct opStar() { /*...*/ }
    }

Now, to read m through an iterator, I could do

    Iterator p;
    int x = (*p).m;

Ignoring for a moment that fact that most of us don't like the syntax,
this will do the job. BUT, in order to do it, an /entire copy/ of a
VeryLargeStruct has been copied onto the stack, just so that I can
then copy one integer, This is what happens when you copy by value. To
make matters worse:

    (*p).m = 10;

Seems to me that, if this compiles at all, opStar will return a
temporary copy of a VeryLargeStruct, and the element m /of that copy/
will be assigned. Again, this is what happens when you return by
value. The obvious solution then is to return by reference...

    struct Iterator
    {
        ref VeryLargeStruct opStar() { /*...*/ }
    }

But - oh wait! We can't return by reference. What a shame! Well - we
could do the next best thing and return by pointer...

    struct Iterator
    {
        VeryLargeStruct * opStar() { /*...*/ }
    }

That works. But now the syntax for dereferencing the iterator has
changed. Now we have to write

    int x = (**p).m;
    (**p).m = 10;

This is the reason I suggest that opStar (...please let it be
opDeref...) be recursive, and that even one star be unnecessary.
Mechanisms have been described on this thread which, so far as I can
see, would work. The syntax we would end up with would be

    int x = p.m;
    p.m = 10;

And that's gotta be a good thing, right?



More information about the Digitalmars-d mailing list