Ali Çehreli:

> S s = { 1 };
> 
> Not good; because we may forget to provide initializers and the 
> remaining members are not even default initialized.

All fields get initialized, unless explicitly told to not be initialized (and 
sometimes they get initialized even if you explicitly tell them to be not 
initialized).

Another simple way to initialize the fields:
struct S {
    int x = 1;
    int y = 2;
}


>(I wrote about this recently; I hope it's just a bug and will get fixed.)<

A recent change done by Walter:
bugzilla 3476 C-style initializer for structs must be disallowed for structs 
with a constructor 
http://dsource.org/projects/dmd/changeset/291


> S s;
> s.x = 1;
> s.y = 2;
> 
> Not good; because that is default initialization plus assignment.

You can change that to:
S s = void;
s.x = 1;
s.y = 2;
But in practice even without the =void LDC is often able to spot the redundancy 
and remove it.


> auto s = S(1, 2);
> 
> Not good, because the right hand side is a struct literal and there is a 
> copy involved.

The compiler isn't dumb, here I think it performs only one initialization. You 
can take a look at the resulting asm when/if you aren't sure. Months ago I have 
filed a bug to llvm asking for better capabilities in detecting and removing 
similar double initializations of dynamic arrays.

 
> Am I giving structs too much 
> attention? Should I just know that they exist but use classes instead?

structs have their purpose, they can be useful to lay memory as you need, or 
for performance purposes, to avoid heap allocations (this is especially true 
for small structs, like a Vector3 or Complex, that coupled with the slow D GC 
and low-tech D compilers produce very slow code if you manage them as objects 
instead of structs). Structs have some downsides too, so you have to be 
careful. In some situations I start coding with classes and later when the code 
works correctly and I have a unittest suite that can be used as a safety net, I 
convert some of them to structs for performance purposes.

Bye,
bearophile

Reply via email to