initialization lists ?

Jarrett Billingsley kb3ctd2 at yahoo.com
Thu Jul 5 05:10:10 PDT 2007


"Daniel919" <Daniel919 at web.de> wrote in message 
news:f6ig0v$u6k$1 at digitalmars.com...
>
> Classes in D are always stored by ref. that's the point, right ?
> MyClass foo = new MyClass(); <- this allocates an instance of MyClass 
> somewhere on the heap and puts a ref to it into foo. So sizeof(foo) is 
> always constant.

Right.
>
>   class Foo {
>     AnotherClass v;
>     Foo(AnotherClass t) { v = t; };
>   };
>   Foo f = new Foo(a);
>
> The assignment way:
> While creating the instance of Foo for f...
> 1. The internal object v gets created inside the instance of f.
> 2. The temp instance t gets created somewhere outside the actual class 
> instance of f.
> 3. a is copied into t.
> 4. t is copied into v.

And as you explain below, since class variables are always references, the 
copying of a to t to v only copies references, a much faster operation than 
copying the entire class.

> Because (in the example above) the instance of v can be located somewhere 
> on the heap (v only holds the reference to it), so it doesn't have to be 
> within the instance of f.
> And the copy of reference can be treated like c++ optimizers do for 
> built-in/intrinsic types. a (reference to an instance of Foo) is copied 
> into v directly, without the need for a temporary object, holding the 
> passed-in ref.
> Or even if it isn't optimized away: Copying of refs is trivial compared to 
> copying of the class's data.

Right.

> Did I get things right ? Otherwise please correct me.

Yep.

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.  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.

Basically the only time large amounts of data are passed on the stack (and 
where something like initialization lists would be useful) are when passing 
structs by value, and hopefully you're not passing too many big ones around. 





More information about the Digitalmars-d mailing list