On 1/20/22 6:01 PM, 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?

The compiler rules aren't enforced based on what code you wrote, it doesn't have the capability of proving that your code doesn't modify things.

Instead, it enforces simple rules that allow prove that const data cannot be modified.

I'll make it into a simpler example:

```d
const int[] arr = [1, 2, 3, 4 5];
int[] arr2 = arr;
```

This code does not modify any data in arr. But that in itself isn't easy to prove. In order to ensure that arr is never modified, the compiler would have to analyze all the code, and every possible way that arr2 might escape or be used somewhere at some point to modify the data. It doesn't have the capability or time to do that (if I understand correctly, this is NP-hard).

Instead, it just says, you can't convert references from const to mutable without a cast. That guarantees that you can't modify const data. However, it does rule out a certain class of code that might not modify the const data, even if it has the opportunity to.

It's like saying, "we don't let babies play with sharp knives" vs. "we will let babies play with sharp knives but stop them just before they stab themselves."

-Steve

Reply via email to