RedBlackTree thin wrapper initialization

Rene Zwanenburg via Digitalmars-d digitalmars-d at puremagic.com
Wed May 28 01:49:41 PDT 2014


On Wednesday, 28 May 2014 at 08:37:14 UTC, Chris wrote:
> On Wednesday, 28 May 2014 at 07:13:37 UTC, BlackEdder wrote:
>> I'm trying to write a thin wrapper around redblacktree, but it 
>> seems every object of the class shares the same copy of 
>> redblacktree. Am I doing something wrong or is this a bug.
>>
>> Minimal code example:
>>
>> import std.array;
>> import std.container;
>> import std.stdio;
>>
>> class A {
>>    auto tree = new RedBlackTree!string();
>> }
>>
>> unittest {
>>    auto a = new A();
>>    a.tree.insert( "a" );
>>    auto b = new A();
>>    writeln( "Should be empty, but is: ", b.tree.array );
>>    writeln( "Should be empty, but has length: ", b.tree.length 
>> );
>> }
>>
>> Which results in the following output:
>> $ rdmd -unittest rbt.d
>> Should be empty, but is: ["a"]
>> Should be empty, but has length: 1
>>
>>
>> I'm using dmd 2.0.65.
>
> Have you tried
>
> class A {
>   RedBlackTree!(string) tree;
>   this() {
>     tree = new RedBlackTree!string();
>   }
> }
>
> Maybe in your implementation all instances of class A share the 
> same underlying instance RedBlackTree, or class RedBlackTree 
> was designed as a singleton (which would seem odd to me).
>
> PS This question would be better suited for the "D learn" forum.

Ninja'd ;)

Also, if you want to avoid repeating long type names an alias can 
help:

class A
{
   alias TreeType = RedBlackTree!string;

   TreeType tree;

   // etc etc.
}

In this case it isn't too bad but some template instantiations 
can get fairly long.


More information about the Digitalmars-d mailing list