Changing elements during foreach

Alexandr Druzhinin drug2004 at bk.ru
Mon Oct 21 07:59:53 PDT 2013


21.10.2013 17:55, Krzysztof Ciebiera пишет:
> On Monday, 21 October 2013 at 10:41:38 UTC, Alexandr Druzhinin wrote:
>> 21.10.2013 17:31, Krzysztof Ciebiera пишет:
>>> void main()
>>> {
>>>     int a[][] = [[1,2,3]];
>>>     foreach(x; a)
>>>     {
>>>         x[0] = 0;
>>>         x ~= 4;
>>>     }
>>>     writeln(a);
>>> }
>>> ...
>>> &) or [0,2,3,4] (python, C++ ref). But [0,2,3]? It was unpleasant
>>> surprise.
>> It's expected.
>> foreach(ref x; a) == C++ with &
>> but without ref you get the first element of a - i.e. [1, 2, 3] then
>> set x[0] = 0 so you get [0, 2, 3]. But when you append 4 you append it
>> to local copy of x - because there is no 'ref'.
>
> So, when exactly my local copy of data should be created? Now it is
> created during appending element to an array (when I switch instructions
> order, first append x ~= 4, then set x[0] to 0, as a result I get
> [1,2,3]). Maybe I should get a warning (like when hiding variable from
> outer scope)?
If you switch instruction order you create local copy and then set x[0] 
in local copy so original is unchanged. But local copy creating depends 
on several thing and happens not every appending in general. Your way is 
not D-ish one. What do you want to do?


More information about the Digitalmars-d-learn mailing list