Why do immutable variables need reference counting?
ag0aep6g
anonymous at example.com
Tue Apr 12 22:23:18 UTC 2022
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.
More information about the Digitalmars-d-learn
mailing list