|
C++(www.cppentry.com) can seem rather fickle about initializing the values of objects. For example, if you say this, - int x;
in some contexts, x is guaranteed to be initialized (to zero), but in others, it’s not. If you say this, - class Point {
- int x, y;
}; ... Point p;
p’s data members are sometimes guaranteed to be initialized (to zero),but sometimes they’re not. If you’re coming from a language whereuninitialized objects can’t exist, pay attention, because this is important.
Reading uninitialized values yields undefined behavior. On some platforms, the mere act of reading an uninitialized value can halt your program. More typically, the result of the read will be semi-random bits, which will then pollute the object you read the bits into, eventually leading to inscrutable program behavior and a lot of unpleasant debugging.
Now, there are rules that describe when object initialization is guaranteed to take place and when it isn’t. Unfortunately, the rules are complicated— too complicated to be worth memorizing, in my opinion. In general, if you’re in the C part of C++(www.cppentry.com) (see Item 1) and initialization would probably incur a runtime cost, it’s not guaranteed to take place. If you cross into the non-C parts of C++(www.cppentry.com), things sometimes change. This explains why an array (from the C part of C++(www.cppentry.com)) isn’t necessarily guaranteed to have its contents initialized, but a vector (from the STL part of C++(www.cppentry.com)) is.
|