C++ Constructor Pop Quiz
Pop quiz: Do these stylistically different declarations affect the behaviour of the code? struct Foo { Foo() = default; int v; }; struct Bar { Bar(); int v; }; Bar::Bar() = default; int main() { Foo f = {}; Bar b = {}; ... } Many developers would reasonably assume that this may affect code generation quality, but otherwise is a style preference. As you might have guessed, because I'm asking, this is not the case. The reason goes back to the first section above on User-provided Constructors. As the constructor for Foo is defaulted on declaration, it is not user-provided. This means that Foo is an aggregate type, and f.v is zero-initialized. However, Bar has a user-provided constructor, albeit created by the compiler as a defaulted constructor. As this constructor does not explicitly initialize Bar::v, b.v will be default-initialized and unsafe to read.
A screenshot presents a C++ pop quiz comparing two nearly identical default constructors. The punchline is that the declarations are not merely stylistic: Foo remains an aggregate with zero-initialized data, while Bar has a user-provided constructor and its member may be left uninitialized. It is shared as a reaction to subtle, surprising language rules that can make seemingly harmless code differences matter. EN: A screenshot presents a C++ pop quiz comparing two nearly identical default constructors. The punchline is that the declarations are not merely stylistic: Foo remains an aggregate with zero-initialized data, while Bar has a user-provided constructor and its member may be left uninitialized. It is shared as a reaction to subtle, surprising language rules that can make seemingly harmless code differences matter.
- @ithueti / 5102 2021-11-17
- Type
- image
- Size
- 800×527 · 48.9 KiB
- Mood
- technical, ironic
- Language
- en
- Added