Originally Posted by
whiteflags
Well I don't think it applies to new as much because new throws an exception much of the time when it fails
That's not my point. Let me show you what I was getting at.
Code:
States* states;
states = new States[100];
for ( std::size_t i = 0; i < 100; ++i )
{
...
}
Months later, the program is extended by additional functionality. The developer inserts a few lines of code between the declaration of the pointer and it's initialization.
Code:
States* states;
if ( someFlag )
{
someFunc();
}
states = new States[100];
for ( std::size_t i = 0; i < 100; ++i )
{
...
}
Add another few months and the developer decides to remove to the recently added stuff (for whatever reason). Unfortunately he ends up removing a little too much.
Code:
States* states;
for ( std::size_t i = 0; i < 100; ++i )
{
...
}
Now mistakes like that happen, but by spreading out declaration and initialization over 2 statements, you're making yourself a lot more vulnerable to such bugs. I've found a whole ton of bugs similar to this in a number of projects I've inherited. We use a dynamic coder checker (IBM Rational Purify), and in fact the most frequent error it finds are UMRs (Uninitialized Memory Read), most of which are a direct result of developers insisting on deferring initialization of local variables until later, when in most cases it could easily be done right then and there. This style of coding is particularly annoying when it is combined with the old C habit of declaring all local variables at the top of the function.