How to cast `shared` away reliably

Nick Treleaven nick at geany.org
Wed Feb 11 21:12:31 UTC 2026


On Wednesday, 11 February 2026 at 16:49:19 UTC, Arafel wrote:
> On 2/11/26 16:02, Paul Backus wrote:
>> Source: https://dlang.org/spec/const3.html
>
> Quite helpful even if still somewhat confusing.
>
> I think it would still make sense to define what a "subtype" is.

Good idea.

> It might feel "intuitive", but the closest I can find is this:
>
> https://dlang.org/spec/type.html#derived-data-types
>
> However, of the items listed there, pointers are indeed showing 
> this behaviour, but functions and delegates aren't.

A type qualifier on a delegate type applies to its context 
pointer, it does nothing for function (pointer) types.

> Also, it wasn't clear to me what classes and structs would do 
> it (they don't, either).

They do:
```d
struct S
{
	int i;
}
shared S s;
pragma(msg, typeof(s.i)); // shared int
```

> So, all in all, this becomes one of the most unintuitive parts 
> of the language. Consider:
>
> ```d
> struct Pointer(T) {
>     T* t;
>     alias this=t;
> }
> void main() {
>     shared(Pointer!int) foo;
>     shared(int *) bar;
>     int i;
>     foo = &i; // FAILS

`foo.t` is `shared(int*)`. You cannot assign `int*` to that.
Note that these work:

```d
     foo = bar;
     foo.t = bar;
```

>     bar = &i; // FAILS

Same as `foo.t = &i`.

>     cast() foo = &i; // WORKS!!

I think due to the `alias this` it is actually doing this:

     (cast() foo).t = &i; // WORKS!!

That is a bit confusing. The cast gives you `Pointer!int`. I 
think the docs here need to mention that:
https://dlang.org/spec/expression.html#cast_qualifier

Note that this does not work:

     cast() foo.t = &i; // error, `shared(int)*` = `int*`

>     cast() bar = &i; // FAILS

Because that does `shared(int)*` = `int*`, which is a type error.

> So, I'm not saying that it's not according to spec, or that 
> it's wrong, but it really _looks like_ the unintended result of 
> applying rules meant for other situations rather than a fully 
> thought-out feature.

I don't think the type qualifiers are at fault, its more how 
casting and `alias this` interact with them.




More information about the Digitalmars-d mailing list