Strange rbtree behaviour

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 7 02:57:47 PDT 2016


On Thursday, July 07, 2016 09:33:38 Arafel via Digitalmars-d-learn wrote:
> public struct B {
>   public auto col = new RedBlackTree!(A,"a.i < b.i");
> }

If you default-initialize a member of a struct, then every instance of that
struct gets that exact same value. In the case of a value type, this results
in completely distinct values, but in the case of a reference type, it's
shared across instances. If you want each struct to have its own
RedBlackTree for col, then you're going to need to use a constructor. And
since there are no default constructors for structs, and you don't want a
constructor that takes an argument, then you should probably use a factory
function. e.g.

struct B
{
    static B factory()
    {
        B b;
        b.col = new typeof(col);
        return b;
    }

    RedBlackTree!(A, "a.i < b.i") col;
}

void main()
{
    auto b = B.factory();
}

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list