D casting broke?

Joerg Joergonson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 19 12:59:28 PDT 2016


import std.stdio;

class X { X Parent; }

class x : X { }

class a : x
{
     void Do()
     {
         auto p = cast(A!a)(this.Parent);  // works as long as we 
are in A
         assert(p !is null);
     }
}


class A(T : a) : X
{
     X Parent = new X();
     T _y = new T();
}

class b : a { }
class B(T : b) : A!T { }

void main(string[] argv)
{
     auto _A = new A!a();
     auto _B = new B!b();
     _A.Parent = _A;
     _A._y.Parent = _A;
     _B.Parent = _B;    // works if _A, since _B is of type _A it 
should still work
     _B._y.Parent = _B; // ...
			
     _A._y.Do();
     _B._y.Do();
	
}


This should be completely valid since B!T' obviously derives from 
A!T directly and we see that T' derives from b which derives from 
a directly. So B!b is an entirely derived from A!a and hence the 
cast should be successful

So, my code crashes because when I do the cast in the base class 
A!T, and it is used in the derived class(which the cast should be 
valid), a null pointer is created which is used in the base 
class. (Basically, B!T doesn't have to have any code in it, just 
create the object, the code in A!T then will crash if such a cast 
exists)


The obviously question: Is there a simple way around this? I'd 
ask, how long to fix but that might take months/years. I can 
override in b and duplicate code but why? That makes life more 
difficult than having things work as they should(having to 
maintain twice is much code is not a solution).










More information about the Digitalmars-d-learn mailing list