Skip to content

Commit 64ee618

Browse files
authored
Merge pull request #2259 from WalterBright/EmptyStructs
add detail about empty structs
2 parents 2d3634a + b5da7d9 commit 64ee618

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

spec/struct.dd

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ $(H2 $(LNAME2 struct_layout, Struct Layout))
6262
the first field and the start of the object.
6363
)
6464

65+
$(P Structs with no fields of non-zero size (aka $(I Empty Structs)) have a size of one byte.)
66+
6567
$(P Non-static $(RELATIVE_LINK2 nested, function-nested D structs), which access the context of
6668
their enclosing scope, have an extra field.
6769
)
@@ -70,11 +72,21 @@ $(H2 $(LNAME2 struct_layout, Struct Layout))
7072
$(OL
7173
$(LI The default layout of the fields of a struct is an exact
7274
match with the $(I associated C compiler).)
75+
$(LI g++ and clang++ differ in how empty structs are handled. Both return `1` from `sizeof`,
76+
however, clang++ does not push them onto the parameter stack while g++ does. This is a
77+
binary incompatibility between g++ and clang++.
78+
dmd follows clang++ behavior for OSX and FreeBSD, and g++ behavior for Linux and other
79+
Posix platforms.
80+
)
81+
$(LI clang and gcc both return `0` from `sizeof` for empty structs. Using `extern "C++"`
82+
in clang++ and g++ does not cause them to conform to the behavior of their respective C compilers.)
7383
))
7484

7585
$(UNDEFINED_BEHAVIOR
7686
$(OL
7787
$(LI The padding data can be accessed, but its contents are undefined.)
88+
$(LI Do not pass or return structs with no fields of non-zero size to `extern (C)` functions.
89+
According to C11 6.7.2.1p8 this is undefined behavior.)
7890
))
7991

8092
$(BEST_PRACTICE
@@ -83,6 +95,8 @@ $(H2 $(LNAME2 struct_layout, Struct Layout))
8395
attributes to describe an exact match. Using a $(DDSUBLINK spec/version, static-assert, Static Assert)
8496
to ensure the result is as expected.)
8597
$(LI Although the contents of the padding are often zero, do not rely on that.)
98+
$(LI Avoid using empty structs when interfacing with C and C++ code.)
99+
$(LI Avoid using empty structs as parameters or arguments to variadic functions.)
86100
))
87101

88102
$(H2 $(LNAME2 POD, Plain Old Data))

0 commit comments

Comments
 (0)