opCast fails when this is null.

Basile B. b2.temp at gmx.com
Sat Oct 28 13:52:36 UTC 2017


On Saturday, 28 October 2017 at 13:24:49 UTC, Mike Wey wrote:
> The following code runs correctly when compiled with ldc 
> (1.4.0) but fails with an assert error when compiled with dmd 
> (2.076 and ldc 1.2.0)
>
>
> ```
> class A
> {
>
> }
>
> class B
> {
> 	T opCast(T)()
> 	{
> 		return this;
> 	}
> }
>
> void main()
> {
> 	A a = null;
> 	B b = null;
>
> 	auto c = cast(Object)a;
> 	auto d = cast(Object)b; // Fails with: 
> core.exception.AssertError at test.d(8): null this
> }
> ```
>
> How would you write an opCast that would handle this case 
> correctly?

Compiler change is required.

This doesn't happen in -release mode. The assert is automatically 
generated by the compiler. It could be disabled, as done here for 
ctors and dtors

https://github.com/dlang/dmd/pull/6982


More information about the Digitalmars-d-learn mailing list