Segfault when casting array of Interface types
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Sep 16 01:39:42 PDT 2014
On Tuesday, 16 September 2014 at 06:27:59 UTC, Klaus wrote:
> On Tuesday, 16 September 2014 at 03:05:57 UTC, Franz wrote:
>> On Tuesday, 16 September 2014 at 03:03:16 UTC, Franz wrote:
>>> On Tuesday, 16 September 2014 at 02:21:42 UTC, rcor wrote:
>>>> I'm back for another round of "is this a bug, or am I doing
>>>> something stupid?".
>>>>
>>>> C and D implement interface I, and I have an array of each.
>>>> I'd like to combine these into one I[], but eventually I'd
>>>> like to cast an element back to its original type.
>>>>
>>>> interface I {}
>>>> class C : I {}
>>>> class D : I {}
>>>>
>>>> void main() {
>>>> C[] c = [new C, new C];
>>>> D[] d = [new D, new D];
>>>> auto i = cast(I[]) c ~ cast(I[]) d;
>>>> assert(cast(C) i[0]); // segfault
>>>> }
>>>>
>>>> casting each array to I[] is fine, but casting an element
>>>> back to C segfaults (even if it weren't a C, it should just
>>>> return null, right?)
>>>
>>> look at what 's auto has created:
>>>
>>> import std.stdio;
>>>
>>> interface I {}
>>> class C : I {}
>>> class D : I {}
>>>
>>> void main() {
>>> C[] c = [new C, new C];
>>> D[] d = [new D, new D];
>>> auto i = cast(I[]) c ~ cast(I[]) d;
>>> writeln(typeof(i).stringof);
>>> }
>>>
>>> Your issue comme from auto.
>>
>> i is a I[]
>
> writing
>
> auto i = cast(I[]) c ~ cast(I[]) d;
>
> is just a horrible way of shortcuting the static typing. You
> write this thinking that i "has to be..." and then you complain
> latter because the cast does not work.
> D is a strongly typed lang. in your example you use "auto"
> because your brain doesnt give you what the type of i has to
> be, which is an error. D is not a scripting lang. You made a
> wrong usage of "auto".
AFACIS there's nothing wrong with his use of casting. It's fine
here, because `I` is a base type of `C` and `D`. If it weren't
for the arrays, the cast wouldn't even be necessary. I think it's
a bug.
More information about the Digitalmars-d-learn
mailing list