Suggestion: class object init value change & new compiler warning message
xs0
xs0 at xs0.com
Wed Aug 23 09:38:05 PDT 2006
Kristian wrote:
> Let we have:
>
> struct Stru {...}
>
> class Obj {
> this() {...}
> this(int val) {...}
>
> bool f() {...}
> }
>
> void func() {
> Stru stru; //valid structure, not NULL as 'obj3'
> Obj obj1 = new Obj;
> Obj obj2 = new Obj(10);
> Obj obj3; //"obj3 = NULL;"
> }
>
> There will be lot of "object = new SomeClass" in code around the globe,
> as in the example.
That's actually good, as one can easily see that a heap allocation is
being done.
> I think it's a much more common situation than
> initializing an object with NULL. Hence objects should be initialized
> with new objects by default. That is, 'func()' would become:
>
> void func() {
> Stru stru;
> Obj obj1; //"obj1 = new Obj;"
> Obj obj2(10); //"obj2 = new Obj(10);"
> Obj obj3 = NULL;
> }
>
> This reduces redundant code: a class name is not anymore used twice per
> object.
> The amount of typing required is also smaller; fewer possible typos.
> (It's pain in the #!%%# to write looogn class names over and over again.)
auto obj = new LooognClassName(..);
> (This suggestion won't break old code.)
It could - if the constructor does something, it will be done more often
than before (and just wildly allocating objects is not a very good idea
either, as it's slow even if mem allocation is all that happens). And,
there's the obvious:
Processor p;
while (auto d = readData()) {
if (p is null) // construct p only if needed
p = new Processor();
p.process(d);
}
if (p) { // will always execute under your proposal
...
}
> Compiler could also optimize the initialization values: if a value is
> assigned to an object before it's used, then it's initialized with NULL
> instead of a new object.
> [snip]
> But can the compiler know which init value to use?
> The very basic checking is done, of course, as follows:
>
> 1) Get the first occurance of an object.
> 2) If it's on the left side of an assignment statement, it's inited with
> NULL.
> 3) Otherwise it's inited with a new object.
If only it were that simple; in reality, it's quite impossible to
determine where an object will be first used (if at all). Which
occurrence is first in the following code?
Foo foo;
if (..) {
foo = ..;
} else {
foo = ..;
}
> And here comes the suggestion #2:
>
> If a variable is used without initialization, the compiler should warn
> about it.
This is practically impossible to get right (and it's really annoying
when the compiler gets it wrong; trust me, I use Java which tries to do
it and it is wrong far too often).
Instead, variables in D get initialized to useless values (or 0 for
integers), so it's hard to miss usage of an uninitialized value (albeit
only at runtime).
xs0
More information about the Digitalmars-d
mailing list