www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Syntax for struct constructors

reply Steve Teale <steve.teale britseyeview.com> writes:
The D2 structs and unions documentation tells how to define a struct 
constructor (that's a mouthful). But it doesn't tell how to use it. Seems 
like if you have say

struct Bar
{
    int[] a;
    this(uint sz) { a.length = sz; }
}

you can do either:

Bar bar = Bar(256);

or:

Bar bar;
bar = bar(256);

but it would be nicer if you could just do:

Bar bar(256);

In any case, it should be documented.
Feb 07 2010
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
Steve Teale wrote:
 The D2 structs and unions documentation tells how to define a struct
 constructor (that's a mouthful). But it doesn't tell how to use it. 
Seems
 like if you have say

 struct Bar
 {
     int[] a;
     this(uint sz) { a.length = sz; }
 }

 you can do either:

 Bar bar = Bar(256);

 or:

 Bar bar;
 bar = bar(256);
You probably meant Bar(256) on the right hand side? Then it's a struct literal. In any case, even if the produced codes are the same; *I think* the latter is actually technically default construction, followed by assignment. Which may involve different operations, depending on the struct...
 but it would be nicer if you could just do:

 Bar bar(256);
I miss that from C++ too. I assumed that there must be reasons related to D's syntax for not allowing that. I've settled to this syntax myself, which is effectively the same as your first above: auto bar = Bar(256);
 In any case, it should be documented.
Ali
Feb 07 2010
parent Kagamin <spam here.lot> writes:
Ali Çehreli Wrote:

  > but it would be nicer if you could just do:
  >
  > Bar bar(256);
 
 I miss that from C++ too. I assumed that there must be reasons related 
 to D's syntax for not allowing that.
This syntax is reserved for function prototypes.
Feb 08 2010