Why do immutable variables need reference counting?

wjoe invalid at example.com
Thu Apr 14 11:42:24 UTC 2022


On Tuesday, 12 April 2022 at 22:23:18 UTC, ag0aep6g wrote:
> On Tuesday, 12 April 2022 at 19:54:13 UTC, wjoe wrote:
>> Especially since it's only a promise and the compiler accepts 
>> this:
>>
>> void foo (const(char)[] arr)
>> {
>>   cast(char[])arr[0..3] = "baz";
>> }
>> string bar = "123";
>> foo(bar);
>> assert(bar=="baz");
>>
>> But I could cast away const and modify the string bar.
>
> No, you could not. You're relying on undefined behavior there. 
> Just because the compiler accepts something, doesn't mean it's 
> ok.
>
> If you want to be guarded against wandering into undefined 
> territory, that's what @safe does. With @safe, the cast doesn't 
> compile.

Undefined behavior yes, but regardless the example proves it can 
be done in @system code.
A few versions ago, possibly due to a bug or regression, the 
compiler didn't complain in @safe code either.

Of course you are correct academically. However, since it's 
possible, I'd wager my last hat that code like this is out in the 
wild.


More information about the Digitalmars-d-learn mailing list