C++ Variable Initialization
Discussions focus on the rules, pitfalls, and safety issues of default and zero-initialization for variables and structs in C++, comparisons to Rust's stricter model, and proposals for improvements like explicit uninitialized markers in future standards.
Activity Over Time
Top Contributors
Keywords
Sample Comments
Good question! I'm not entirely sure, perhaps it's defense against the compiler optimizing the initialization out?
Rust mandates that every field in a user-defined type is initialized at once. How do you propose to retrofit that into C without "constructors"?
constinit allows for constant initialization. Why, how enlightening! Now... what is constant initialization?
Ideally, there would be a keyword for it. So ‘A a;’ would not compile. You’d need to do ‘A a{};’ or something like ‘noinit A a;’ to tell the compiler you’re sure you know what you are doing!
i said "if a type has a constructor". but if you are fiddling around with ints and chars and the like, then you will need to initialise them. i have been writing c++ since the mid80s and have never found this to be a problem, or at least no more than it would be to use an uninitialised int variable in C.
I think that was the author's point. You _can_ use them this way but it's a hassle and most people don't do it. The language itself doesn't protect you against zero-initialisation errors, even though it could.
Initialisation in C++ is just footguns all the way down.
that’s just a choice by the language designer. nothing prohibits initialization at runtime.
I suspect that to many C++ programmers, most initializations of structs have unpredictable side effects because of how complex they are ;)
You're the first who has told me he doesn't like default initialization!