https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124069
Bug ID: 124069
Summary: Zero initialization for array of structs containing
anonymous union
Product: gcc
Version: 16.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: aaron.puchert at sap dot com
Target Milestone: ---
The following code:
#include <new>
struct Element {
union { int data; };
Element() = default;
};
struct S {
const void* other = nullptr;
Element array[100];
};
void makeS(void* address) {
new (address) S;
}
with -O2 -std=c++20 compiles to (GCC trunk x86):
_Z5makeSPv:
subq $8, %rsp
addq $8, %rdi
movl $400, %edx
xorl %esi, %esi
movq $0, -8(%rdi)
call memset
addq $8, %rsp
ret
So the array is zero-initialized, even though
* S is only default-initialized,
* array has no initializer,
* data has no initializer.
Interestingly, changing almost anything about the example code makes the zero
initialization disappear, for example:
* removing "other" or just its initializer,
* replacing "union { int data; }" by "int data",
* removing "Element() = default;".
Zero initialization also disappears with -std=c++17, but I'm not aware of any
C++20 changes that would explain this.