Michel Fortin wrote:
On 2009-02-09 06:41:59 -0500, Ary Borenszweig <a...@esperanto.org.ar> said:
How would you do this?
X x;
if(someCondition) {
x = new SomeX();
} else {
x = new SomeOtherX();
}
Well, the declaration could be transformed to this:
X x = new X;
But since x is not used before being reassigned (for all code paths),
the compiler could just leave it uninitialized until you do the
assignement yourself. But then perhaps the "new X" should not be elided
unless the constructor and and destructor are pure.
I don't trust that the compiler would do that.
Another question is what happens when X is an abstract class.
Or when X has no default constructor. Or when X's default constructor
allocates non-memory resources. Or when X's default constructor depends
on global variables that those conditionals set and segfaults or throws
when those globals are not in a consistent state. Or when X is a really
huge class or does a lot of computation in its constructor and
allocating it takes an unreasonable amount of time.
Any case in which the default constructor has side effects or
preconditions is a problem.