Skip to content

Commit 4f9ac81

Browse files
authored
Merge pull request #2322 from WalterBright/struct-default
rewrite struct disable construction text
2 parents 4201c36 + b03909b commit 4f9ac81

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

spec/struct.dd

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -486,27 +486,52 @@ constructor will have their `.init` values upon destruction.)
486486
}
487487
------
488488

489+
$(H2 $(LNAME2 disable_default_construction, Disabling Default Struct Construction))
490+
489491
$(P If struct constructor is annotated with $(D @disable) and has
490-
empty parameter, the struct is disabled construction without calling
491-
other constructor.
492+
an empty $(GLINK2 function, ParameterList), the struct has disabled default construction.
493+
The only way it can be constructed is via a call to another constructor with a non-empty
494+
$(I ParameterList).
492495
)
493-
------
496+
497+
$(P A struct with a disabled default constructor, and no other constructors, cannot
498+
be instantiated other than via a $(GLINK2 declaration, VoidInitializer).)
499+
500+
$(P A disabled default constructor may not have a $(GLINK2 function, FunctionBody).)
501+
502+
$(P If any fields have disabled default construction, the struct default construction is
503+
also disabled.)
504+
505+
---
494506
struct S
495507
{
496508
int x;
497509

498-
// Disables default construction, function body can be empty.
510+
// Disables default construction
499511
@disable this();
500512

501513
this(int v) { x = v; }
502514
}
515+
struct T
516+
{
517+
int y;
518+
S s;
519+
}
503520
void main()
504521
{
505-
//S s; // default construction is disabled
506-
//S s = S(); // also disabled
507-
S s = S(1); // construction with calling constructor
522+
S s; // error: default construction is disabled
523+
S t = S(); // error: also disabled
524+
S u = S(1); // constructed by calling `S.this(1)`
525+
S v = void; // not initialized, but allowed
526+
S w = { 1 }; // error: cannot use { } since constructor exists
527+
S[3] a; // error: default construction is disabled
528+
S[3] b = [S(1), S(20), S(-2)]; // ok
529+
T t; // error: default construction is disabled
508530
}
509-
------
531+
---
532+
533+
$(BEST_PRACTICE Disabling default construction is useful when the default value,
534+
such as `null`, is not acceptable.)
510535

511536
$(H2 $(LEGACY_LNAME2 StructPostblit, struct-postblit, Struct Postblits))
512537

0 commit comments

Comments
 (0)