Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do fundamental C++ types have an unknown initial value?

When will a fundamental C++ type, such as int or float, have an unknown initial value?

How does the type of memory allocation factor in, if at all? What about the declaration? What if it's a member of a class/struct/union? Is C++11 different from C++03 or C++98?

I have my suspicions, but no idea if my knowledge is complete (or correct, for that matter)

like image 396
Drew Dormann Avatar asked Jan 14 '23 06:01

Drew Dormann


1 Answers

Any POD data (including all fundamental types) will have an unknown value when both:

  • it doesn't have static memory allocation (it's instead created on the stack or with new)
  • it isn't initialized, including empty initialization and/or constructor initialization lists

Global/static variables, of all types, are set to zero as part of the startup process before main is called. Constructors are called for types that have constructors before main 1.

Anything not initialized in the constructor is also unknown.

Edit: to clarify, std::string is a good example of "constructor not initializing everything" - if you have a local std::string str;, then str will have a defined "empty string" content, but the content of the actual buffer, or indeed what the buffer points at may not be set to anything meaningful at all - as the implementation may determine based on the length [or some other way] whether there is a buffer available or not once we start using the string to store stuff].

Edit2: As the comment explains, you can also have "hybrid" cases, where parts of a structure is being initialized, e.g. a struct that contains some elements of "plain data" and some elements that have constructors. The ones that have constructors will have their constructor called. The plain data will not be initialized.

1 It may well be that the code running constructors is part of, or called from inside the "main" function - but if that is the case, it will be "before any of your code in main is started".

like image 86
Mats Petersson Avatar answered Feb 01 '23 11:02

Mats Petersson