Weird rule for immutable
Steven Schveighoffer
schveiguy at gmail.com
Sat Apr 11 20:01:22 UTC 2020
On 4/10/20 9:45 PM, Victor Porton wrote:
> On Saturday, 11 April 2020 at 01:26:28 UTC, Adam D. Ruppe wrote:
>> On Saturday, 11 April 2020 at 01:19:29 UTC, Victor Porton wrote:
>>> Why this is disallowed?
>>
>> Immutable means it NEVER changes. If you want it to just temporarily
>> not change, that's what const is for.
>
> Yes, specification reads this way by me, too.
>
> But is there any practical reason that the specification disallows the
> following?
>
> int[] x = [];
> {
> immutable y = cast(immutable)x;
> }
> x = [1, 2];
So let me modify your example to address Adam's point:
int[] x = [1,2];
{
immutable y = cast(immutable)x;
}
x[] = 5;
And let's do something else:
void foo(const(int)[] z) {writeln(z);}
foo(x);
Theoretically, the compiler could assume that x's data has become
immutable and by logical deduction, write "[1, 2]".
It's usually the case that if you invoke undefined behavior, the
compiler can do anything it wants under the given assumptions.
-Steve
More information about the Digitalmars-d
mailing list