initialization lists ?

Daniel919 Daniel919 at web.de
Thu Jul 5 07:49:31 PDT 2007


> Something else to keep in mind is that D doesn't really allow for 
> uninitialized members.  When you declare a class, the compiler generates a 
> "static" instance of it with all the members initialized to their defaults 
> (either one that you specify with i.e. "int i = 5;" or with the type's 
> default).  When you instantiate a class or struct, it will allocate the 
> memory and then copy the static instance into that block, so that there are 
> no uninitialized members.

This shows exactly what you explained:
----------------------------------------------------------------------------
import std.stdio;

class SubClass {
	static this() { writefln("static SubClass created"); }
	this() { writefln("SubClass created"); }
	static ~this() { writefln("static SubClass destroyed"); }
	~this() { writefln("SubClass destroyed"); }
}

class MyClass {
	SubClass subclass;
	this() { writefln("MyClass created"); }
	static this() { writefln("static MyClass created"); }
	~this() { writefln("MyClass destroyed"); }
	static ~this() { writefln("static MyClass destroyed"); }
}



void main() {
	writefln("----");
	MyClass myclass1 = new MyClass();
	delete myclass1;
	writefln("----");
}
----------------------------------------------------------------------------

static SubClass created
static MyClass created
----
MyClass created
MyClass destroyed
----
static MyClass destroyed
static SubClass destroyed

> It would be pretty difficult (but not impossible) 
> for the compiler to do initialization list optimizations, because it'd have 
> to alternate between copying out of the static initializer and copying from 
> the stack.  It might even trash the cache, ending up with about the same 
> performance as now.

Yes, it would have to make sure that the temporary object is not used 
except for getting its value assigned to the according member object of 
the class.


Thanks for your replies, Jarrett !

Daniel



More information about the Digitalmars-d mailing list