initialization lists ?
Jarrett Billingsley
kb3ctd2 at yahoo.com
Wed Jul 4 19:46:47 PDT 2007
"Daniel919" <Daniel919 at web.de> wrote in message
news:f6hbud$1iga$1 at digitalmars.com...
>
> So, according to the article
> http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6,
> this is prefered...
>
> class Foo {
> int x;
> Foo(int i) : x(i) {};
> };
>
> ...over
>
> class Foo {
> int x;
> Foo(int i) { x = i; };
> };
>
>
> In the former case, when the ctor "creates" the class, it directly
> assigns the value of i to x, as if someone had declared it like:
> class Foo {
> int x = i; //Impossible of course
> Foo(int i) : x(i) {};
> };
>
> In the latter case "i" is the temporary object, that only
> exists to get its value assigned to x.
>
>
> How does D handle this ? There are no initialization lists.
One, your example is a little wrong: that FAQ also mentions that "There is
no performance difference if the type of x_ is some built-in/intrinsic type,
such as int." So you should be using a class type instead.
Two, D doesn't allow for the same kind of object semantics that C++ does.
C++ allows classes to have their memory allocated inside other classes,
which is why using initialization lists are faster: rather than creating
that temp object and copying it into the memory inside 'this', it just runs
the constructor for the internal object on the memory already inside 'this'.
D only allows classes to be allocated on the heap (well, they can be
allocated on the stack in some circumstances, but not in the general case
like in C++). Therefore, if one of your class's members is another class
that needs to be constructed, it's going to have to be new'ed anyway, so
there's no way to optimize it.
D does, however, have structs which can have their memory allocated inside
other aggregates (structs, classes, unions). In this case, when you use the
"fake" struct ctor (a static S opCall), the compiler can optimize the call
to this function and it becomes as fast as a simple assignment to the
struct's members. (Structs are rumored to be getting ctors soon, so
hopefully it will be less arcane and "magical"-looking.)
More information about the Digitalmars-d
mailing list