First Draft: cast(ref T)... as shorthand for *cast(T*)&...
Walter Bright
newshound2 at digitalmars.com
Mon Jan 20 23:09:24 UTC 2025
On 1/20/2025 1:07 AM, IchorDev wrote:
> On Saturday, 18 January 2025 at 07:31:40 UTC, Walter Bright wrote:
>> Proposed by Manu https://github.com/dlang/dmd/issues/20644
>>
>> PR: https://github.com/dlang/dmd/pull/20728
>
> I would really like an actual DIP that I can read.
It wouldn't be any more than what I wrote in:
https://github.com/dlang/dlang.org/pull/4164
> First: I think this type of cast should be `@safe` where conservatively
> possible. For example, I can’t think of any reason that casting from `int` to
> `float` in this way shouldn’t be `@safe`. For structs it’s more complicated, but
> you could try to check if both are POD, make sure the size is equal or less, etc.
> Reinterpretation into `bool` is obviously always unsafe. ;)
That's a good idea for a future enhancement.
> Second: Is there a way to make this syntax also simplify these 2 similar patterns?
> ```d
> T[] foo = (cast(T*)malloc(T.sizeof * n))[0..n];
> ```
A template?
> ```d
> void[] foo = (cast(void*)&bar)[0..bar.sizeof];
> ```
I haven't really thought about that. But this also works and is simpler and
easier to read:
```
void[] foo = cast(void[])((&bar)[0 .. 1]);
```
> Third: This is a long shot, but should we make it so that casting to a larger
> type is `@safe` by populating the remaining space with zeroes?
> ```d
> short foo = 10;
> auto baz = cast(ref int)foo; //remaining 2 bytes filled with zeroes
> ```
That wouldn't be good because it would stomp on whatever is next in memory.
More information about the dip.development
mailing list