Skip to content

Commit 9d73eb1

Browse files
authored
[spec/struct] More on struct destructors (#3639)
Update following #3638. Tweak wording. Document field destruction. Mention destructor is called again after destroy. Remove assigning init - this doesn't call the dtor if opAssign is defined.
1 parent a9d5469 commit 9d73eb1

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

spec/struct.dd

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1770,8 +1770,8 @@ void main()
17701770

17711771
$(H2 $(LEGACY_LNAME2 StructDestructor, struct-destructor, Struct Destructors))
17721772

1773-
$(P Destructors are called when an object goes out of scope, or
1774-
$(RELATIVE_LINK2 assign-overload, before an assignment).
1773+
$(P Destructors are called implicitly when an object goes out of scope, or
1774+
$(RELATIVE_LINK2 assign-overload, before an assignment) (by default).
17751775
Their purpose is to free up resources owned by the struct
17761776
object.
17771777
)
@@ -1801,8 +1801,43 @@ void main()
18011801
}
18021802
---
18031803
)
1804-
$(P The destructor can also be called early using $(REF1 destroy, object)
1805-
or by assigning the struct's `init` property.)
1804+
$(P If the struct has a field of another struct type which itself has a destructor,
1805+
that destructor will be called at the end of the parent destructor. If there is no
1806+
parent destructor, the compiler will generate one. Similarly, a
1807+
static array of a struct type with a destructor will have the destructor
1808+
called for each element when the array goes out of scope.)
1809+
1810+
$(SPEC_RUNNABLE_EXAMPLE_RUN
1811+
---
1812+
struct S
1813+
{
1814+
char c;
1815+
1816+
~this()
1817+
{
1818+
import std.stdio;
1819+
writeln("S(", c, ") is being destructed");
1820+
}
1821+
}
1822+
1823+
struct Q
1824+
{
1825+
S a;
1826+
S b;
1827+
}
1828+
1829+
void main()
1830+
{
1831+
Q q = Q(S('a'), S('b'));
1832+
S[2] arr = [S('0'), S('1')];
1833+
// destructor called for arr[1], arr[0], q.b, q.a
1834+
}
1835+
---
1836+
)
1837+
1838+
$(P A destructor for a struct instance can also be called early using
1839+
$(REF1 destroy, object). Note that the destructor will still
1840+
be called again when the instance goes out of scope.)
18061841

18071842
$(P Struct destructors are used for $(DDSUBLINK spec/glossary, raii, RAII).)
18081843

@@ -1813,7 +1848,7 @@ $(H2 $(LNAME2 union-field-destruction, Union Field Destruction))
18131848
a destructor. When a union goes out of scope, destructors for its fields *are not called*.
18141849
If those calls are desired, they must be inserted explicitly by the programmer:)
18151850

1816-
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
1851+
$(SPEC_RUNNABLE_EXAMPLE_RUN
18171852
---
18181853
struct S
18191854
{

0 commit comments

Comments
 (0)