Why separate variable definition and initialization in C++?

I'm currently working on some quite old C++ code and often find things like

int i;
i = 42;

or

Object* someObject = NULL;
someObject = new Object();

or even

Object someObject;
someObject = getTheObject();

I completely understand what this code does but I really have no idea when such a separation of variable definition and initialization could be helpful. I searched for some explanations but always ended up with member initialization lists or the question when you should define your local variables.

In the end, I don't understand the reason why someone could have intentionally written this code. It just splits definition and initialization up into two subsequent lines and creates overhead – in the last case it creates an object using the default constructor only to destroy it in the next line.

I wonder whether I should simply change the code to

int i = 42;
Object* someObject = new Object();
Object someObject = getTheObject();

Could this lead to any problems?

21
задан sth 23 March 2011 в 11:04
поделиться