immutable(ubyte)[] to receive
Steven Schveighoffer
schveiguy at gmail.com
Thu Jan 20 20:52:35 UTC 2022
On 1/20/22 5:21 AM, bauss wrote:
> On Thursday, 20 January 2022 at 10:19:37 UTC, bauss wrote:
>> On Thursday, 20 January 2022 at 10:18:03 UTC, bauss wrote:
>>> On Thursday, 20 January 2022 at 09:38:55 UTC, Alexey wrote:
>>>>
>>>> Buffer[] t ;
>>>> t ~= cast(Buffer)"sdfsdfsdf";
>>>> t ~= cast(Buffer)"sdfsdfsdf";
>>>> immutable(Buffer[]) ti = cast(immutable)t;
>>>>
>>>
>>> This is undefined behavior.
>>>
>>> Since ti isn't really immutable.
>>>
>>> You can still modify the original buffer (t).
>>>
>>> You should use const instead of immutable and, that goes for your
>>> functions too.
>>>
>>> They should receive const and not immutable.
>>>
>>> Summary:
>>>
>>> Mutable means: Anyone and anything can modify it.
>>> Immutable means: Nobody will modify it, not here and not anywhere
>>> else. Initialization is only allowed, but not pointing to anything
>>> that has mutable references.
>>> Const means: I promise not to modify it, but another mutable
>>> reference might.
>>>
>>> In your example t is a mutable reference, where as ti is an immutable
>>> reference.
>>>
>>> That's illegal and constitutes as UB (Undefined behavior)
>>>
>>> It would have been legal if you either used const or if you made an
>>> immutable duplication of t with ex. t.idup.
>>
>> Oh wait, I just noticed Buffer is an alias to an immutable array.
>>
>> Ignore what I just said...
>
> I'm too fast again, well don't ignore entirely what I said, since you
> still modify an immutable reference by appending to t, I believe.
>
> I'm not 100% sure about this one, but I'm 99% sure.
Note that casting from mutable to immutable is actually defined as long
as you don't modify the data after that (as seen
[here](https://dlang.org/spec/const3.html#creating_immutable_data)).
It's actually technically defined to cast to mutable from immutable as
long as you don't modify the mutable data (this can be a requirement if
you are calling a C function for example that takes a mutable reference
that you know won't modify the data for that call).
Appending to immutable array data is not considered a modification,
because within the context of the language, an append is like tacking on
unallocated data to the end of the array.
-Steve
More information about the Digitalmars-d
mailing list