On 1/20/22 15:01, forkit wrote:
> On Thursday, 20 January 2022 at 22:31:17 UTC, Steven Schveighoffer wrote:
>>
>> Because it would allow altering const data.
>>
>
> I'm not sure I understand. At what point in this function is valuesArray
> modified, and thus preventing it being passed in with const?
>
> // ---
>
> int[][int][] CreateDataSet
> ref const int[] idArray, ref int[][] valuesArray, const int numRecords)
> {
>      int[][int][] records;

Elements of records are mutable.

>      records.reserve(numRecords);
>
>      foreach(i, const id; idArray)
>          records ~= [ idArray[i] : valuesArray[i] ];

If that were allowed, you could mutate elements of record and would break the promise to your caller.

Aside: There is no reason to pass arrays and associative arrays as 'ref const' in D as they are already reference types. Unlike C++, there is no copying of the elements. When you pass by value, just a couple of fundamental types are copied.

Furthermore and in theory, there may be a performance penalty when an array is passed by reference because elements would be accessed by dereferencing twice: Once for the parameter reference and once for the .ptr property of the array. (This is in theory.)

void foo(ref const int[]) {}  // Unnecessary
void foo(const int[]) {}      // Idiomatic
void foo(in int[]) {}         // Intentful :)

Passing arrays by reference makes sense when the function will mutate the argument.

Ali

Reply via email to