Sending an immutable object to a thread

Frank Pagliughi via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 24 11:55:24 PDT 2015


On Friday, 24 July 2015 at 18:02:58 UTC, Ali Çehreli wrote:
> Although the example casts to void*, ubyte* and others are 
> possible as well, and casting back to the correct class type 
> seems to work:

Thanks, Ali.

I just tried a few things, and apparently, you don't need to go 
to a different type or void. You can make it a pointer the the 
actual type, which might be good for self-documentation or 
pattern matching. But what I find somewhat odd and fascinating is 
what you show, that for the reference, "r":

   cast(D*)r != &r

So this code all works out:

   import std.stdio;

   class B
   {
     int i;
     this(int i) { this.i = i; }
   }

   void main()
   {
     auto r1 = new B(42),
          r2 = r1;

     writefln("Address of reference r1: %s", &r1);
     writefln("Address of reference r2: %s", &r2);

     writefln("Address of object r1   : %s", cast(B*)r1);
     writefln("Address of object r2   : %s", cast(B*)r2);

     assert(cast(B*)r1 == cast(B*)r2);

     assert(cast(B*)r1 != &r1);
     assert(cast(B*)r2 != &r2);
   }

and prints:

   Address of reference r1: 7FFF1D4E4C70
   Address of reference r2: 7FFF1D4E4C78
   Address of object r1   : 7F01CD506000
   Address of object r2   : 7F01CD506000


So then, of course, I hope/wonder/assume that the pointer to the 
heap is sufficient to keep the heap memory alive, and that this 
would be OK from the GC perspective to do something like this:

   B* make_b_thing(int i) { cast(B*) new B(i); }

That seems to work, but I guess I should try to force the garbage 
collector to run to see if I can crash the program.

***BUT***: The really, really weird thing is that even though you 
*think* that you have a pointer to a B object, you don't really. 
Dereferencing is accepted by the compiler, but it plays a nasty 
trick on you:

   B* p = make_b_thing(42);
   writefln("Address of pointer: %s", p);

   writefln("Value of i: %s", p.i);
   writefln("Value of i: %s", (*p).i);
   writefln("Value of i: %s", (cast(B)p).i);

This compiles and runs fine, but produces:

   Address of pointer: 7F7EE77CF020
   Value of i: 4445040
   Value of i: 4445040
   Value of i: 42

Maybe it's my C++ background talking, but that seems a bit 
counter-intuitive.


More information about the Digitalmars-d-learn mailing list