What is the case against a struct post-blit default constructor?

monarch_dodra monarchdodra at gmail.com
Fri Oct 12 02:31:36 PDT 2012


On Friday, 12 October 2012 at 08:34:31 UTC, Jonathan M Davis 
wrote:
>> 
>> Try that code defining S as RefCounted!int and see what 
>> happens.
>
> That just means that the problem goes further than just 
> invariants. It's still
> a big problem for invariants.
>
> - Jonathan M Davis

I appologize, but I don't see how this is a "big problem". It is 
no different then doing:

S s = void;
s.__ctor(args);

Initializing something to void _is_ unsafe, and must be used with 
precautions. opAssign is no different. If you want it called, 
then you _HAVE_ to make sure the target is valid first.

The only reason:
int a = void;
a = 5;

works is because a doesn't define an opAssign, and int doesn't 
have any invalid states anyways.

It's once S becomes complex that you can't just go rushing in 
assigning and constructing without proper initialization.

Using emplace makes the "problem" go away entirely*, as it will 
just do a straight-up memcopy if that is "good enough" (no extra 
cost for ints), and do "what is needed" for the rest (".init + 
.__ctor" or ".init + opAssign").

alias RefCounted!int S;
int i = void;
S s1 = void;
S s2 = void;
emplace(&i, 5);     //OK! Do a memcpy assignement
emplace(&s1, 5);    //OK! Do a .init memcpy + .__ctor
emplace(&s2, S(5)); //OK! Do a .init memcpy + .opAssign**

*Technically, once my fix goes through. It currently chokes.
**Actually, RefCounted has a CC, so that is the one that will be 
used. Just wanted to illustrate it *could* be one of the things 
that could happen.

//--------
Bask on subject, I _have_ started working with invariants. I 
think they are nice, but there indeed some times where you'd wish 
they wouldn't trigger.

How about the @noinvariant function attribute? Sounds like a 
simple enough solution.

At that point, the developer can just insert "assert(&this);" in 
said functions, if and where he judges it necessary.



More information about the Digitalmars-d mailing list