casting class pointer

Simen kjaeraas simen.kjaras at gmail.com
Fri Nov 19 02:02:58 PST 2010


Jesse Phillips <jessekphillips+D at gmail.com> wrote:

> 	 auto hi = "hello" in b.all;
>
> 	 auto foo = cast(B) hi;

> The result was that b.label wasn't the same, and printing out stuff  
> resulted in a bunch of garbage.

Not surprising. hi is pointing to a reference (pointer) to a B instance,
not a proper B, and certainly not the one you hope for. Thus, random
garbage from the memory surrounding the reference is outputted.


> The questions I have are, should casting a class pointer to a class  
> change its behavior so it just gives you the class? Is is there a use  
> case for the current behavior? And should I bother working to reproduce  
> this?

The idea behind the in operator for AAs is that it indicate whether there
was something at the specified index, by returning null if there wasn't.
IOW, 'a in AA'  does not return a class reference, and shouldn't.

You may have reasons to put nulls in your AA, in which case the returned
B* may be non-null, while *hi is null. I have not thought of a good use
case for this, though. However, the main reason I see is symmetry. Having
to explain that for T[U] t, 'a in t' returns a T* is ok. Having to explain
that this simple rule breaks when T is a class, is not good.

Last, a cast is a message to the compiler of "Trust me, I know what I'm
doing". That could mean that your B* is actually a B (a reference), that
somehow ended up being a B*. In such a case, the only reasonable thing to
do is interpreting the bits as a B instead of a B*.

What you should do in the above code is
     auto foo = *hi;

tl;dr: making the casting of class reference pointers to class references
do the shortcut of interpreting the pointer as a reference is asymmetric
and limits the language.

-- 
Simen


More information about the Digitalmars-d mailing list