Limits of implicit conversion of class arrays

FeepingCreature feepingcreature at gmail.com
Sat Mar 23 12:00:57 UTC 2024


On Saturday, 23 March 2024 at 11:04:04 UTC, Dmitry Olshansky 
wrote:
> On Saturday, 23 March 2024 at 09:08:45 UTC, Per Nordlöw wrote:
>> Is there a reason why
>>
>> ```d
>> class Base {}
>> class Derived : Base {}
>>
>> @safe pure nothrow unittest {
>> 	Base b;
>> 	Derived d;
>> 	b = d; // pass
>>
>> 	Base[] bs;
>> 	Derived[] ds;
>> 	bs ~= ds; // pass
>> 	bs = ds; // fail [1], should pass
>> 	bs = cast(Base[])ds; // fail [2], should pass
>> }
>> ```
>>
>> fails as
>>
>> [1]: cannot implicitly convert expression `ds` of type 
>> `Derived[]` to `Base[]`
>> [2]: cast from `Derived[]` to `Base[]` not allowed in safe code
>>
>> ?
>
> The first and second is unsound (infamously allowed in Java). 
> Once you cast the slice you can populate it with Derived2 
> objects that are not Derived, hence breaking type safety of the 
> ds slice.
>
>> Dmitry Olshansky
> CEO @ Glow labs
> https://olshansky.me

Note that it works if the classes are const:

```d
	const(Base)[] bs;
	const(Derived)[] ds;
	bs ~= ds; // pass
	bs = ds; // pass
	bs = cast(const(Base)[])ds; // pass
```

Exactly because you can't replace existing entries.


More information about the Digitalmars-d-learn mailing list