Newbie comments about D

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Thu Aug 17 14:24:44 PDT 2006


Kristian wrote:
> 
> --- 1 ---
> 
> Well, how about this:
> 
> The compiler could initialize a variable with a new object or NULL 
> depending on if a value is assigned to it before it's used. For example:
> 
> void f() {
>     C c1;  //c1 = new C;
>     C c2;  //c2 = NULL;
> 
>     if(c1.f() == 1) {...}
> 
>     c2 = getSomeObject();
> }
> 
> This unifies all the variable declarations, and you don't need to write 
> long " = new ..." initializations!
> 
> This also means, of course, that an object is always initialized for you 
> (as it should, you have provided a constructor for it, haven't you?). 
> The compiler just optimized it's initial value, i.e. a new object is not 
> allocated when it's unnecessary.

The problem is that the compiler can't tell. While it's possible in 
trivial cases, one can write arbitrarily complex code, which means the 
compiler needs to be sufficiently smart to be sure. Walter has referred 
to this problem before with initialization, and the fact that it is 
annoying when the compiler is stupid and gets it wrong.
> 
> 
> --- 4 ---
> 
> By the way, the 'auto' attribute is used with local variables, so would 
> a word 'local' be a more logical choice?
> 
> void f() {
>     local C c = new C;
>     ...
> }
A huge change of code would be required for that.
> --- 5 ---
> 
> Hmm, could it be possible to automatically add auto/local attribute to 
> objects that are not returned (by a function) and that are not assigned 
> to anything? For example:
> 
> class File {...}  //the file is closed in the destructor
> 
> void f() {
>     File f = new File;  //auto File f = new File;
> 
>     f.open("myfile.txt");
>     f.doSomething();
> }
There's nothing in the spec that prohibits the compiler doing that right 
now. /Enforcing/ it in the spec could be interesting, though. I still 
think it is safer to annotate it properly, though. Otherwise you may get 
into problems where someone else uses that code you showed, and 
accidentally returns it to something else. Then its behaviour would 
suddenly change and it wouldn't be destroyed.
> 
> Also, auto/local objects could remain in the stack instead of the heap 
> (but that's only an issue of optimization).
Again, no prohibition. Walter has even mentioned that as a future 
improvement.



More information about the Digitalmars-d mailing list