Strange rbtree behaviour

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 7 02:46:25 PDT 2016


On Thursday, 7 July 2016 at 09:40:57 UTC, Lodovico Giaretta wrote:
> Initially it looks very surprising, but then if you add 
> `writeln(B.init.col[]);` you can easily find out what's going 
> on.
>
> And I'm quite sure it's expected behaviour.

An RBTree is just a pointer to the memory containing the actual 
tree. Your `col`s have different addresses because they are 
different copies of the same pointer. If you cast `col` to a 
pointer and write the address it's pointing at, you find out that 
the two structures are pointing to the same memory.

This is because assignments used in a structure declaration are 
not re-executed for each instantiation. Instead, they are 
executed one to create the `.init` member of the type, which is 
then bit-copied on every other instance. So your code does this:

B.init.col = new RBTree(...);

B b1 = B.init;
B b2 = B.init;


More information about the Digitalmars-d-learn mailing list