How to modify an element in a range/collection using its member function?

Jens Mueller jens.k.mueller at gmx.de
Thu May 3 03:03:40 PDT 2012


Hi,

in Phobos opIndex returns a copy due to the reasons outlined in TDPL p.
378 (hiding the storage). Even though I find the argumentation
convincing and opIndexAssign/opIndexOpAssign usually makes the design
sound I ran into surprises when using member functions.
I use the Zip the range which has the same behavior, i.e. return a copy.
Consider a random-access range/container R of say 10 points.

auto c = R!Point(10);

If Point has member functions you naturally write buggy code as I did
(operating on a temporary Point).
c[2].changePointSomehow();

The work around is
auto tmp = c[2];
tmp.changePointSomehow();
c[2] = tmp;
which does not look good to me. Simply things should be simple.
swap won't work as changePointSomehow() does not return the modified
Point.

Should std.range.Zip be an exception and return by reference? Because it
actually does not store anything. I don't like this as Zip may perform
some optimization for indexing.

What is a good solution when using member functions on a
range's/container's element?

Note, the problem only applies when storing structs because classes
behave like references.

Jens


More information about the Digitalmars-d mailing list