questions around mutating range algorithms, const, and return ref

Simen Kjærås simen.kjaras at gmail.com
Mon Jan 29 12:10:16 UTC 2018


On Monday, 29 January 2018 at 11:36:26 UTC, aliak wrote:
>> You don't want to mutate const elements anyway. It would be 
>> breaking a promise that other parts of the program may be 
>> depending on. I would return a filtered-out range:
>
> Right, I want to mutate the range though, not the elements. So 
> moving things from one location is not considered as a const 
> violation in c++ for eg, maybe the D way is different though?

Consider this case:

immutable(int)[] a = [1,2,3];
immutable(int)* b = &a[1];

You're free to slice the array or pop elements off its front or 
back, but if you change the order of elements, the value that b 
points to will change. D does not allow this.

You can create a new array with the elements moved into the 
locations you want, and with another layer of indirections 
(int*[]) you can move the elements of the array without mutating 
the values.

> Any reading material there?

https://dlang.org/const-faq.html


> Also hasMobileElements!(const int[]) is true, so that means I 
> can move elements around right?

hasMobileElements checks if the value of front can be moved as in 
move constructors, not as in 'can be moved to a different spot in 
the range'. I will admit the name does little to unconfuse this 
point.

--
   Simen


More information about the Digitalmars-d-learn mailing list