Why aren't pointers initialized with NULL by default?
Solution 1:
We all realize that pointer (and other POD types) should be initialized.
The question then becomes 'who should initialize them'.
Well there are basically two methods:
- The compiler initializes them.
- The developer initializes them.
Let us assume that the compiler initialized any variable not explicitly initialized by the developer. Then we run into situations where initializing the variable was non trivial and the reason the developer did not do it at the declaration point was he/she needed to perform some operation and then assign.
So now we have the situation that the compiler has added an extra instruction to the code that initializes the variable to NULL then later the developer code is added to do the correct initialization. Or under other conditions the variable is potentially never used. A lot of C++ developers would scream foul under both conditions at the cost of that extra instruction.
It's not just about time. But also space. There are a lot of environments where both resources are at a premium and the developers do not want to give up either.
BUT: You can simulate the effect of forcing initialization. Most compilers will warn you about uninitialized variables. So I always turn my warning level to the highest level possible. Then tell the compiler to treat all warnings as errors. Under these conditions most compilers will then generate an error for variables that are un-initialized but used and thus will prevent code from being generated.
Solution 2:
Quoting Bjarne Stroustrup in TC++PL (Special Edition p.22):
A feature's implementation should not impose significant overheads on programs that do not require it.
Solution 3:
Because initialisation takes time. And in C++, the very first thing you should do with any variable is to explicitly initialise it:
int * p = & some_int;
or:
int * p = 0;
or:
class A {
public:
A() : p( 0 ) {} // initialise via constructor
private:
int * p;
};
Solution 4:
Because one of the mottos of C++ is :
You don't pay for what you don't use
For this very reason, the operator[]
of the vector
class does not check if the index is out of bounds, for instance.