Class inside a Struct?
Ary Borenszweig via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 30 16:55:36 PST 2015
On 1/30/15 7:29 PM, Ali Çehreli wrote:
> 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
>
Thanks for explanation. I was sure there was some reason why you didn't
suggest it. It's an unfortunate inconsistency, I think. I don't know why
`.init` is so important or why the default value of a type has any
importance at all.
More information about the Digitalmars-d-learn
mailing list