-
-
Notifications
You must be signed in to change notification settings - Fork 379
/
Copy pathstruct.dd
2519 lines (2079 loc) · 69.6 KB
/
struct.dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Ddoc
$(SPEC_S Structs and Unions,
$(HEADERNAV_TOC)
$(H2 $(LNAME2 intro, Introduction))
$(P Whereas $(DDLINK spec/class, Classes, classes) are reference types,
structs and unions are value types.
Structs are simple aggregations of data and their
associated operations on that data.
)
$(GRAMMAR
$(GNAME StructDeclaration):
$(D struct) $(GLINK_LEX Identifier) $(D ;)
$(D struct) $(GLINK_LEX Identifier) $(GLINK AggregateBody)
$(GLINK2 template, StructTemplateDeclaration)
$(I AnonStructDeclaration)
$(GNAME AnonStructDeclaration):
$(D struct) $(GLINK AggregateBody)
)
$(GRAMMAR
$(GNAME UnionDeclaration):
$(D union) $(GLINK_LEX Identifier) $(D ;)
$(D union) $(GLINK_LEX Identifier) $(GLINK AggregateBody)
$(GLINK2 template, UnionTemplateDeclaration)
$(I AnonUnionDeclaration)
$(GNAME AnonUnionDeclaration):
$(D union) $(GLINK AggregateBody)
)
$(GRAMMAR
$(GNAME AggregateBody):
$(D {) $(GLINK2 module, DeclDefs)$(OPT) $(D })
)
$(P The following example declares a struct type with a single integer field:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
struct S
{
int i;
}
void main()
{
S a;
a.i = 3;
S b = a; // copy a
a.i++;
assert(a.i == 4);
assert(b.i == 3);
}
---
)
$(P For local variables, a struct/union instance is allocated on the stack
by default. To allocate on the heap, use $(DDSUBLINK spec/expression, new_expressions,
`new`), which gives a pointer.)
$(PANEL
A $(LNAME2 struct-pointer, pointer to a struct) or union is automatically
dereferenced when using the `.` operator to access members.
---
S* p = new S;
assert(p.i == 0); // `p.i` is the same as `(*p).i`
---
$(NOTE There is no `->` operator as in C.)
)
$(P A struct can contain multiple fields which are stored sequentially.
Conversely, multiple fields in a union use overlapping storage.)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
union U
{
ubyte i;
char c;
}
void main()
{
U u;
u.i = 3;
assert(u.c == '\x03');
u.c++;
assert(u.i == 4);
}
---
)
$(H2 $(LNAME2 members, Members))
$(H3 $(LNAME2 struct-members, Struct Members))
$(P A struct definition can contain:)
$(UL
$(LI Fields)
$(LI $(DDSUBLINK spec/attribute, static, Static) fields)
$(LI $(RELATIVE_LINK2 anonymous, Anonymous Structs and Unions))
$(LI $(DDSUBLINK spec/class, member-functions, member functions)
$(UL
$(LI static member functions)
$(LI $(RELATIVE_LINK2 struct-constructor, Constructors))
$(LI $(RELATIVE_LINK2 struct-destructor, Destructors))
$(LI $(RELATIVE_LINK2 Invariant, Invariants))
$(LI $(DDLINK spec/operatoroverloading, Operator Overloading, Operator Overloading))
)
$(LI $(RELATIVE_LINK2 alias-this, Alias This))
$(LI Other declarations (see $(GLINK2 module, DeclDef)))
)
)
$(P A struct is defined to not have an identity; that is,
the implementation is free to make bit copies of the struct
as convenient.)
$(BEST_PRACTICE
$(OL
$(LI Bit fields are supported with the
$(LINK2 https://dlang.org/phobos/std_bitmanip.html#bitfields, bitfields) template.)
))
$(H3 $(LNAME2 union-members, Union Members))
$(P A union definition can contain:)
$(UL
$(LI Fields)
$(LI $(DDSUBLINK spec/attribute, static, Static) fields)
$(LI $(RELATIVE_LINK2 anonymous, Anonymous Structs and Unions))
$(LI $(DDSUBLINK spec/class, member-functions, member functions)
$(UL
$(LI static member functions)
$(LI $(RELATIVE_LINK2 UnionConstructor, Constructors))
$(LI $(DDLINK spec/operatoroverloading, Operator Overloading, Operator Overloading))
)
$(LI $(RELATIVE_LINK2 alias-this, Alias This))
$(LI Other declarations (see $(GLINK2 module, DeclDef)))
)
)
$(H3 $(LNAME2 recursive-types, Recursive Structs and Unions))
$(P Structs and unions may not contain a non-static instance of themselves,
however, they may contain a pointer to the same type.
)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
S* ptr; // OK
S[] slice; // OK
S s; // error
S[2] array; // error
static S global; // OK
}
---
)
$(H2 $(LNAME2 struct_layout, Struct Layout))
$(P The non-static data members of a struct are called $(I fields). Fields are laid
out in lexical order. Fields are aligned according to the $(DDSUBLINK spec/attribute, align, Align Attribute)
in effect.
Unnamed padding is inserted between fields to align fields. There is no padding between
the first field and the start of the object.
)
$(P Structs with no fields of non-zero size (aka $(I Empty Structs)) have a size of one byte.)
$(P Non-static $(RELATIVE_LINK2 nested, function-nested D structs), which access the context of
their enclosing scope, have an extra field.
)
$(IMPLEMENTATION_DEFINED
$(OL
$(LI The default layout of the fields of a struct is an exact
match with the $(I associated C compiler).)
$(LI g++ and clang++ differ in how empty structs are handled. Both return `1` from `sizeof`,
however, clang++ does not push them onto the parameter stack while g++ does. This is a
binary incompatibility between g++ and clang++.
dmd follows clang++ behavior for OSX and FreeBSD, and g++ behavior for Linux and other
Posix platforms.
)
$(LI clang and gcc both return `0` from `sizeof` for empty structs. Using `extern "C++"`
in clang++ and g++ does not cause them to conform to the behavior of their respective C compilers.)
))
$(UNDEFINED_BEHAVIOR
$(OL
$(LI The padding data can be accessed, but its contents are undefined.)
$(LI Do not pass or return structs with no fields of non-zero size to `extern (C)` functions.
According to C11 6.7.2.1p8 this is undefined behavior.)
))
$(BEST_PRACTICE
$(OL
$(LI When laying out a struct to match an externally defined layout, use align
attributes to describe an exact match. Using a $(DDSUBLINK spec/version, static-assert, Static Assert)
to ensure the result is as expected.)
$(LI Although the contents of the padding are often zero, do not rely on that.)
$(LI Avoid using empty structs when interfacing with C and C++ code.)
$(LI Avoid using empty structs as parameters or arguments to variadic functions.)
))
$(H2 $(LNAME2 POD, Plain Old Data))
$(P A struct or union is $(I Plain Old Data) (POD) if it meets the following criteria:)
$(OL
$(LI it is static, or not nested)
$(LI it has no postblits, copy constructors, destructors, or assignment operators)
$(LI it has no fields that are themselves non-POD)
)
$(BEST_PRACTICE Structs or unions that interface with C code should be POD.)
$(H2 $(LNAME2 opaque_struct_unions, Opaque Structs and Unions))
$(P Opaque struct and union declarations do not have an $(GLINK AggregateBody):)
---
struct S;
union U;
struct V(T);
union W(T);
---
$(P The members are completely hidden to the user, and so the only operations
on those types are ones that do not require any knowledge of the contents
of those types. For example:)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S;
S.sizeof; // error, size is not known
S s; // error, cannot initialize unknown contents
S* p; // ok, knowledge of members is not necessary
---
)
$(BEST_PRACTICE They can be used to implement the
$(LINK2 https://en.wikipedia.org/wiki/Opaque_pointer, PIMPL idiom).)
$(H2 $(LNAME2 initialization, Initialization))
$(H3 $(LNAME2 default_struct_init, Default Initialization of Structs))
$(P Struct fields are by default initialized to whatever the
$(GLINK2 declaration, Initializer) for the field is, and if none is supplied, to
the $(DDSUBLINK spec/property, init, default initializer) for the field's type.
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
struct S { int a = 4; int b; }
S x; // x.a is set to 4, x.b to 0
---
)
$(P The default initializers are evaluated at compile time.)
$(H3 $(LNAME2 static_struct_init, Static Initialization of Structs))
$(GRAMMAR
$(GNAME StructInitializer):
$(D {) $(I StructMemberInitializers)$(OPT) $(D })
$(GNAME StructMemberInitializers):
$(I StructMemberInitializer)
$(I StructMemberInitializer) $(D ,)
$(I StructMemberInitializer) $(D ,) $(GSELF StructMemberInitializers)
$(GNAME StructMemberInitializer):
$(GLINK2 declaration, NonVoidInitializer)
$(GLINK_LEX Identifier) $(D :) $(GLINK2 declaration, NonVoidInitializer)
)
$(P If a $(I StructInitializer) is supplied,
each $(I StructMemberInitializer) initializes a matching field:)
* A $(I StructMemberInitializer) using the $(I Identifier : NonVoidInitializer) syntax
may appear in any order. The identifier must match a field name.
* If the first $(I StructMemberInitializer) does not specify an *Identifier*,
it refers to the first field in the $(GLINK StructDeclaration).
* A subsequent *NonVoidInitializer* without an *Identifier* refers to the next field
(in lexical order) after the one referred to in the previous *StructMemberInitializer*.
$(P Any field not covered by a $(I StructMemberInitializer) is default initialized.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
struct S { int a, b, c, d = 7; }
S r; // r.a = 0, r.b = 0, r.c = 0, r.d = 7
S s = { a:1, b:2 }; // s.a = 1, s.b = 2, s.c = 0, s.d = 7
S t = { c:4, b:5, a:2, d:5 }; // t.a = 2, t.b = 5, t.c = 4, t.d = 5
S u = { 1, 2 }; // u.a = 1, u.b = 2, u.c = 0, u.d = 7
S v = { 1, d:3 }; // v.a = 1, v.b = 0, v.c = 0, v.d = 3
S w = { b:1, 3 }; // w.a = 0, w.b = 1, w.c = 3, w.d = 7
---
)
$(P Initializing a field more than once is an error:)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
S x = { 1, a:2 }; // error: duplicate initializer for field `a`
---
)
$(H3 $(LNAME2 default_union_init, Default Initialization of Unions))
$(P Unions are by default initialized to whatever the
$(GLINK2 declaration, Initializer) for the first field is, and if none is supplied, to
the default initializer for the first field's type.
If the union is larger than the first field, the remaining bits
are set to 0.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
union U { int a = 4; long b; }
U x; // x.a is set to 4, x.b to an implementation-defined value
---
)
$(P It is an error to supply initializers for members other than the first one.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
union V { int a; long b = 4; } // error: union field `b` with default initialization `4` must be before field `a`
union W { int a = 4; long b = 5; } // error: overlapping default initialization for `a` and `b`
---
)
$(P The default initializer is evaluated at compile time.)
$(IMPLEMENTATION_DEFINED The values the fields other than the
default initialized field are set to.)
$(H3 $(LNAME2 static_union_init, Static Initialization of Unions))
$(P Unions are initialized
$(RELATIVE_LINK2 static_struct_init, similarly to structs), except that only
one member initializer is allowed. If the member initializer does not specify
an identifier, it will initialize the first member of the union.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
union U { int a; double b; }
U u = { 2 }; // u.a = 2
U v = { b : 5.0 }; // v.b = 5.0
---
)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
U w = { 2, 3 }; // error: overlapping initialization for field `a` and `b`
---
)
$(P If the union is larger than the initialized field, the remaining bits
are set to 0.)
$(IMPLEMENTATION_DEFINED The values the fields other than the
initialized field are set to.)
$(H3 $(LNAME2 dynamic_struct_init, Dynamic Initialization of Structs))
$(P The $(RELATIVE_LINK2 static_struct_init, static initializer syntax)
can also be used to initialize non-static variables.
The initializer need not be evaluable at compile time.)
$(SPEC_RUNNABLE_EXAMPLE_RUN
----
struct S { int a, b, c, d = 7; }
void test(int i)
{
S q = { 1, b:i }; // q.a = 1, q.b = i, q.c = 0, q.d = 7
}
----
)
$(P Structs can be dynamically initialized from another
value of the same type:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
----
struct S { int a; }
S t; // default initialized
t.a = 3;
S s = t; // s.a is set to 3
----
)
$(P If the struct has a $(RELATIVE_LINK2 struct-constructor, constructor), and
the struct is initialized with a value that is of a different type,
then the constructor is called:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
----
struct S
{
int a;
this(int v)
{
this.a = v;
}
}
S s = 3; // sets s.a to 3 using S's constructor
----
)
$(P If the struct does not have a constructor but
$(DDSUBLINK spec/operatoroverloading, FunctionCall, `opCall`) is
overridden for the struct, and the struct is initialized with a value
that is of a different type, then the $(D opCall) operator is called:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
----
struct S
{
int a;
static S opCall(int v)
{
S s;
s.a = v;
return s;
}
static S opCall(S v)
{
assert(0);
}
}
S s = 3; // sets s.a to 3 using S.opCall(int)
S t = s; // sets t.a to 3, S.opCall(S) is not called
----
)
$(H3 $(LNAME2 dynamic_union_init, Dynamic Initialization of Unions))
$(P The $(RELATIVE_LINK2 static_union_init, static initializer syntax)
can also be used to initialize non-static variables.
The initializer need not be evaluable at compile time.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
union U { int a; double b; }
void test(int i)
{
U u = { a : i }; // u.a = i
U v = { b : 5.0 }; // v.b = 5.0
}
---
)
$(H2 $(LEGACY_LNAME2 StructLiteral, struct-literal, Struct Literals))
$(P A struct literal consists of the name of the struct followed
by a parenthesized named argument list:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
struct S { int x; float y; }
S s1 = S(1, 2); // set field x to 1, field y to 2
S s2 = S(y: 2, x: 1); // same as above
assert(s1 == s2);
---
)
$(P
If a struct has a $(RELATIVE_LINK2 struct-constructor, constructor)
or a member function named `opCall`, then
struct literals for that struct are not possible. See also
$(DDSUBLINK spec/operatoroverloading, FunctionCall, opCall operator overloading)
for the issue workaround.)
$(P Struct literals are syntactically like function calls.)
$(PANEL
Arguments are assigned to fields as follows:
1. If the first argument has no name, it will be assigned to the struct field that is defined first lexically.
1. A named argument is assigned to the struct field with the same name.
It is an error if no such field exists.
1. Any other argument is assigned to the next lexically defined struct field relative to the preceding argument's struct field.
It is an error if no such field exists, i.e. when the preceding argument assigns to the last struct field.
1. It is also an error to assign a field more than once.
1. Any fields not assigned a value are initialized with their respective default initializers.
**Note:**
These rules are consistent with function calls, see $(DDSUBLINK spec/function, argument-parameter-matching, Matching Arguments to Parameters).
)
$(P
If there is a union field in the struct, only one
member of the union can be initialized inside a
struct literal. This matches the behaviour for union literals.
)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
struct S { int x = 1, y = 2, z = 3; }
S s0 = S(y: 5, 6, x: 4); // `6` is assigned to field `z`, which comes after `y`
assert(s0.z == 6);
S s1 = S(y: 5, z: 6); // Field x is not assigned, set to default initializer `1`
assert(s1.x == 1);
//S s2 = S(y: 5, x: 4, 5); // Error: field `y` is assigned twice
//S s3 = S(z: 2, 3); // Error: no field beyond `z`
---
)
$(H2 $(LNAME2 union-literal, Union Literals))
$(P A union literal is like a struct literal, but only one field can
be initialized with an initializer expression.
The remainder of the union's memory is initialized to zero.
)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
union U
{
byte a;
char[2] b;
}
U u = U(2);
assert(u.a == 2);
assert(u.b == [2, 0]);
---
)
$(H2 $(LNAME2 anonymous, Anonymous Structs and Unions))
$(P An anonymous struct or union can be declared as a member of a
parent class, struct or union by omitting the identifier after `struct` or `union`.
An anonymous struct declares sequentially stored fields in the
parent type. An anonymous union declares overlapping fields in
the parent type.)
$(P An anonymous union is useful inside a class or struct to share
memory for fields, without having to name a parent field with a
separate union type.)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
struct S
{
int a;
union
{
byte b;
char c;
}
}
S s = S(1, 2);
assert(s.a == 1);
assert(s.b == 2);
assert(s.c == 2); // overlaps with `b`
---
)
$(P Conversely, an anonymous struct is useful inside a union to
declare multiple fields that are stored sequentially.)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
union U
{
int a;
struct
{
uint b;
bool c;
}
}
U u = U(1);
assert(u.a == 1);
assert(u.b == 1); // overlaps with `a`
assert(u.c == false); // no overlap
---
)
$(H2 $(LEGACY_LNAME2 struct_instance_properties, struct_properties, Struct Properties))
$(TABLE
$(THEAD Name, Description)
$(TROW $(D .alignof), Size boundary struct needs to be aligned on)
$(TROW $(D .tupleof), A $(DDSUBLINK spec/template, variadic-templates, symbol sequence)
of all struct fields - see
$(DDSUBLINK spec/class, tupleof, class `.tupleof`) for more details.)
)
$(H3 $(LNAME2 struct_field_properties, Struct Field Properties))
$(TABLE2 Struct Field Properties,
$(THEAD Name, Description)
$(TROW $(D .offsetof), Offset in bytes of field from beginning of struct)
)
$(H2 $(LEGACY_LNAME2 ConstStruct, const-struct, Const, Immutable and Shared Structs))
$(P A struct declaration can have a storage class of
$(CODE const), $(CODE immutable) or $(CODE shared). It has an equivalent
effect as declaring each member of the struct as
$(CODE const), $(CODE immutable) or $(CODE shared).
)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
----
const struct S { int a; int b = 2; }
void main()
{
S s = S(3); // initializes s.a to 3
S t; // initializes t.a to 0
t = s; // error, t.a and t.b are const, so cannot modify them.
t.a = 4; // error, t.a is const
}
----
)
$(H2 $(LNAME2 UnionConstructor, Union Constructors))
$(P Unions are constructed in the same way as structs.)
$(H2 $(LEGACY_LNAME2 Struct-Constructor, struct-constructor, Struct Constructors))
$(P Struct constructors are used to initialize an instance of a struct when a more
complex construction is needed than is allowed by
$(RELATIVE_LINK2 static_struct_init, static initialization) or a
$(RELATIVE_LINK2 struct-literal, struct literal).
)
$(P Constructors are defined with a function name of `this` and have no return value.
The grammar is the same as for the class $(GLINK2 class, Constructor).
)
$(P A struct constructor is called by the name of the struct followed by
$(GLINK2 function, Parameters).
)
$(P If the $(GLINK2 function, ParameterList) is empty,
the struct instance is default initialized.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int x, y = 4, z = 6;
this(int a, int b)
{
x = a;
y = b;
}
}
void main()
{
S a = S(4, 5); // calls S.this(4, 5): a.x = 4, a.y = 5, a.z = 6
S b = S(); // default initialized: b.x = 0, b.y = 4, b.z = 6
S c = S(1); // error, matching this(int) not found
}
---
)
$(P Named arguments will be forwarded to the constructor and match parameter names, not struct field names.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int x;
int y;
this(int y, int z) { this.x = y; this.y = z; }
}
S a = S(x: 3, y: 4); // Error: constructor has no parameter named `x`
S b = S(y: 3, 4); // `y: 3` will set field `x` through parameter `y`
---
)
$(P A $(I default constructor) (i.e. one with an empty $(GLINK2 function, ParameterList))
is not allowed.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int x;
this() { } // error, struct default constructor not allowed
}
---
)
$(H3 $(LNAME2 delegating-constructor, Delegating Constructors))
$(P A constructor can call another constructor for the same struct
in order to share common initializations. This is called a
$(I delegating constructor):
)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int j = 1;
long k = 2;
this(long k)
{
this.k = k;
}
this(int i)
{
// At this point: j=1, k=2
$(CODE_HIGHLIGHT this)(6); // delegating constructor call
// At this point: j=1, k=6
j = i;
// At this point: j=i, k=6
}
}
---
)
$(P The following restrictions apply:)
$(OL
$(LI If a constructor's code contains a delegating constructor call, all
possible execution paths through the constructor must make exactly one
delegating constructor call:
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int a;
this(int i) { }
this(char c)
{
c || this(1); // error, not on all paths
}
this(wchar w)
{
(w) ? this(1) : this('c'); // ok
}
this(byte b)
{
foreach (i; 0 .. b)
{
this(1); // error, inside loop
}
}
}
---
)
)
$(LI It is illegal to refer to $(D this) implicitly or explicitly
prior to making a delegating constructor call.)
$(LI Once the delegating constructor returns, all fields are considered
constructed.)
$(LI Delegating constructor calls cannot appear after labels.)
)
$(P See also: $(DDSUBLINK spec/class, delegating-constructors, delegating class constructors).)
$(H3 $(LNAME2 struct-instantiation, Struct Instantiation))
$(P When an instance of a struct is created, the following steps happen:)
$(OL
$(LI The raw data is statically initialized using the values provided
in the struct definition.
This operation is equivalent to doing a memory copy of a static
version of the object onto the newly allocated one.
)
$(LI If there is a constructor defined for the struct,
the constructor matching the argument list is called.
)
$(LI If struct invariant checking is turned on, the struct invariant
is called at the end of the constructor.
)
)
$(H3 $(LNAME2 constructor-attributes, Constructor Attributes))
$(P A constructor qualifier (`const`, `immutable` or `shared`) constructs the object instance
with that specific qualifier.
)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S1
{
int[] a;
this(int n) { a = new int[](n); }
}
struct S2
{
int[] a;
this(int n) immutable { a = new int[](n); }
}
void main()
{
// Mutable constructor creates mutable object.
S1 m1 = S1(1);
// Constructed mutable object is implicitly convertible to const.
const S1 c1 = S1(1);
// Constructed mutable object is not implicitly convertible to immutable.
immutable i1 = S1(1); // error
// Mutable constructor cannot construct immutable object.
auto x1 = immutable S1(1); // error
// Immutable constructor creates immutable object.
immutable i2 = immutable S2(1);
// Immutable constructor cannot construct mutable object.
auto x2 = S2(1); // error
// Constructed immutable object is not implicitly convertible to mutable.
S2 m2 = immutable S2(1); // error
// Constructed immutable object is implicitly convertible to const.
const S2 c2 = immutable S2(1);
}
---
)
$(P Constructors can be overloaded with different attributes.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
struct S
{
this(int); // non-shared mutable constructor
this(int) shared; // shared mutable constructor
this(int) immutable; // immutable constructor
}
void fun()
{
S m = S(1);
shared s = shared S(2);
immutable i = immutable S(3);
}
---
)
$(H4 $(LNAME2 pure-constructors, Pure Constructors))
$(P If the constructor can create a unique object (i.e. if it is `pure`),
the object is implicitly convertible to any qualifiers.
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
struct S
{
this(int) pure;
// Based on the definition, this creates a mutable object. But the
// created object cannot contain any mutable global data.
// Therefore the created object is unique.
this(int[] arr) immutable pure;
// Based on the definition, this creates an immutable object. But
// the argument int[] never appears in the created object so it
// isn't implicitly convertible to immutable. Also, it cannot store
// any immutable global data.
// Therefore the created object is unique.
}
void fun()
{
immutable i = immutable S(1); // this(int) pure is called
shared s = shared S(1); // this(int) pure is called
S m = S([1,2,3]); // this(int[]) immutable pure is called
}
---
)
$(H3 $(LNAME2 disable_default_construction, Disabling Default Struct Construction))
$(P If a struct constructor is annotated with $(D @disable) and has
an empty $(GLINK2 function, ParameterList), the struct has disabled default construction.
The only way it can be constructed is via a call to another constructor with a non-empty
$(I ParameterList).
)
$(P A struct with a disabled default constructor, and no other constructors, cannot
be instantiated other than via a $(GLINK2 declaration, VoidInitializer).)
$(P A disabled default constructor may not have a $(GLINK2 function, FunctionBody).)
$(P If any fields have disabled default construction, struct default construction is
also disabled.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
struct S
{
int x;
// Disables default construction
@disable this();
this(int v) { x = v; }
}
struct T
{
int y;
S s;
}
void main()
{
S s; // error: default construction is disabled
S t = S(); // error: also disabled
S u = S(1); // constructed by calling `S.this(1)`
S v = void; // not initialized, but allowed
S w = { 1 }; // error: cannot use { } since constructor exists
S[3] a; // error: default construction is disabled
S[3] b = [S(1), S(20), S(-2)]; // ok
T t; // error: default construction is disabled
}
---
)
$(BEST_PRACTICE Disabling default construction is useful when the default value,
such as `null`, is not acceptable.)
$(H3 $(LNAME2 field-init, Field initialization inside a constructor))
$(P In a constructor body, if a delegating constructor is called,
all field assignments are considered assignments.
Otherwise, the first instance of field assignment is
its initialization, and assignments of the form `field = expression`
are treated as equivalent to `typeof(field)(expression)`.
The values of fields may be read before initialization or construction
with a delegating constructor.
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
struct S
{
int num;
int ber;
this(int i)
{
num = i + 1; // initialization
num = i + 2; // assignment
ber = ber + 1; // ok to read before initialization
}
this(int i, int j)
{
this(i);
num = i + 1; // assignment
}
}
---
)
$(P If the field type has an $(DDSUBLINK spec/operatoroverloading, assignment, `opAssign`)