Class inside a Struct?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 30 14:29:34 PST 2015


On 01/30/2015 01:28 PM, Ary Borenszweig wrote:

 > On 1/30/15 5:28 PM, Ali Çehreli wrote:
 >> On 01/30/2015 11:59 AM, chardetm wrote:
 >>
 >>  > struct Container {
 >>  >
 >>  >      private RedBlackTree!int _rbtree = new RedBlackTree!int;
 >>
 >> I think you are expecting the new expression to be be executed for every
 >> object individually. It is not the case: That new expression determines
 >> the initial value of the _rbtree for every single object of type
 >> Container. As a result, they will all be sharing the same tree.
 >>
 >> The best solution is
 >>
 >> 1) Remove the new expression:
 >> 2) Use a static opCall:
 >
 > Why not use this() ?

In fact, I think a better solution is to use a constructor that takes 
the tree:

     this(RedBlackTree!int rbtree)  // <-- good practice
                                    // ("parameterize from above")
     {
         _rbtree = rbtree;
     }

However, I thought that OP did not want the users know about that 
member. So, as you say, the next option that comes to mind is to use the 
default constructor:

     this()
     {
         _rbtree = new RedBlackTree!int;
     }

Unfortunately, D does not allow defining the default constructor for 
structs:

Error: constructor deneme.Container.this default constructor for structs 
only allowed with @disable and no body

The reason is, the default constructor happens to be the .init value of 
that type and it must be known at compile time.

Ali



More information about the Digitalmars-d-learn mailing list