cas and interfaces

Johannes Loher johannes.loher at fg4f.de
Tue Dec 25 22:07:07 UTC 2018


On Monday, 24 December 2018 at 11:23:32 UTC, Johan Engelen wrote:
> On Sunday, 23 December 2018 at 14:07:04 UTC, Johannes Loher 
> wrote:
>> [...]
>
> The types of the 2nd and 3rd arguments of `cas` do not have to 
> be the same, and aren't in your case. I think what's happening 
> is that you are overwriting `testInterface` with a pointer to a 
> TestClass which is not a valid TestInterface pointer. And then 
> the program does something invalid because, well, you enter UB 
> land.
> Fixed by:
> ```
> cas(&testInterface, testInterface, cast(shared(TestInterface)) 
> new shared TestClass).writeln;
> ```
> Note the cast!
>
> Whether this is a bug in `cas` or not, I don't know. The `cas` 
> template checks whether the 3rd can be assigned to the 1st 
> argument (`*here = writeThis;`) which indeed compiles _with_ an 
> automatic conversion. But then the implementation of `cas` does 
> not do any automatic conversions (casts to `void*`). Hence the 
> problem you are seeing.
>
> -Johan

Thanks a lot for the info, that clarifies things a bit. But it 
still leaves the question, why it works correctly when inheriting 
from an abstract class instead of implementing an interface... 
Any idea about why that?


More information about the Digitalmars-d-learn mailing list