digitalmars.D.learn - Casting a class variable to void*
- Manuel Maier (53/53) Apr 10 2016 I'm not sure whether I've found a bug or if I found some very
- ag0aep6g (3/5) Apr 10 2016 Looks like a bug to me. And it's already been filed:
I'm not sure whether I've found a bug or if I found some very strange but intended behavior. If it is indeed intended behavior, I'd like to know the rationale behind it because this one surprised me a lot when I found it out after 16+ hours of debugging... Have a look at this code snippet: ``` import std.stdio; struct Data {} class Foo { Data data; alias data this; } class Bar {} class Baz { int data = 0xDeadBeef; alias data this; } void main() { auto foo = new Foo(); //auto rawFoo = cast(void*)foo; // Doesn't compile auto rawFoo = *cast(void**)&foo; // This works... auto bar = new Bar(); auto rawBar = cast(void*)bar; // This works, as expected. auto baz = new Baz(); auto rawBaz = cast(void*)baz; // Compiles, but... writefln("foo: 0x%0.8x", rawFoo); writefln("bar: 0x%0.8x", rawBar); writefln("baz: 0x%0.8x", rawBaz); } ``` Here's the output: ``` foo: 0x02341010 bar: 0x02341020 baz: 0xdeadbeef ``` So, when I cast a class variable to void* I expect to get the pointer to the class' content, no matter what the class' content may be. However, when the class is implicitly convertible to something else via `alias this` it tries to cast that instead of trying the class itself first. I understand that a class variable is supposed to act as the class type itself, not a pointer/reference to it, so when I ask that class variable for something that the underlying class doesn't have, the `alias this` is consulted. But in the case above, the class variable itself is perfectly convertible to a void* already, so why would it have to go through `alias this` first? Seems like precedence is messed up for classes and `alias this`. So, is this a bug, or is it intended behavior? In case of the latter, I'd gladly add it to the documentation. By the way, I'm using DMD v2.070.2
Apr 10 2016
On 11.04.2016 00:06, Manuel Maier wrote:So, is this a bug, or is it intended behavior? In case of the latter, I'd gladly add it to the documentation.Looks like a bug to me. And it's already been filed: https://issues.dlang.org/show_bug.cgi?id=13392
Apr 10 2016