In C++, how can one programmatically determine whether an object is default-initialized or left uninitialized — without relying on reading the standard, documentation, or source code?
For example:
int i;
std::string s;
Here, i
is an uninitialized variable with indeterminate value, whereas s
is default-initialized to an empty string.
Reads from uninitialised variables are a hangover from C++'s roots in C, and a major source of bugs. Of course, defining a variable without initialising it before writing to it (say conditionally) prior to reading can be a useful feature if you want every last iota of performance, but in the modern world this miniscule performance gain in a few circumstances doesn't seem worth the huge risk of accidentally introducing undefined behaviour.
Your question as to whether this uninitialised state can be detected programmatically (do you mean at runtime?) is an interesting one, because if there were a general mechanism one might expect the whole issue to be avoided by coding standards enforcing enabling of the checks (which of course there isn't).
The language is evolving, however, and in the spirit of your question and the focus on compile time evaluation, I would consider these options as "programmatically" determining whether a variable is uninitialised by guaranteeing that no such variables exist:
auto
. It is then required that variables are initialised at declaration (otherwise the compiler can't determine their type) and therefore you know they can never be in an uninitialised state.