Proposal : allocations made easier with non nullable types.

Denis Koroskin 2korden at gmail.com
Mon Feb 9 06:40:52 PST 2009


Christopher Wright Wrote:

> Michel Fortin wrote:
> > On 2009-02-09 06:41:59 -0500, Ary Borenszweig <ary at 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.

1) It is a valid C++ construct, and I don't remember having any problem with it.

2) It's just a shortcut for Foo foo = new Foo(). If you don't plan to instanciate the instance immediately, i.e. you want to leave it as null, you should mark it as nullable:

Foo? foo; // no ctor call made



More information about the Digitalmars-d mailing list