Strange rbtree behaviour

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


On Thursday, 7 July 2016 at 09:33:38 UTC, Arafel wrote:
> Hi!
>
> I am seeing what it seems to me a very strange behavior with 
> rbtrees:
>
> ---
> import std.stdio;
> import std.container.rbtree;
>
> public struct A {
> 	public int i;
> 	
> 	public this (int _i) {
> 		this.i = _i;
> 	}
> }
>
> public struct B {
> 	public auto col = new RedBlackTree!(A,"a.i < b.i");
> }
>
> void main() {
> 	B b1;
> 	B b2;
> 	b1.col.insert(A(5));
> 	
> 	static assert(&b1 != &b2);
> 	assert(&(b1.col) != &(b2.col));
> 	writeln(b1.col.length, " ", b2.col.length);
> 	writeln(b1.col[], " ", b2.col[]);
> }
> ---
>
> I get the (to me) surprising result of:
>
> ---
> 1 1
> [A(5)] [A(5)]
> ---
>
> Is this the expected result? If so, why? I'd have expected two 
> new empty but different rbtrees to be created, and in fact 
> that's what happen if I declare them as local variables inside 
> main().
>
> In this case, two different rbtrees are indeed created (as seen 
> with the assertion), but they apparently point to the same 
> underlying data...
>
> Thanks!

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.


More information about the Digitalmars-d-learn mailing list