Classes or stucts :: Newbie

bearophile bearophileHUGS at lycos.com
Sun Dec 19 12:38:36 PST 2010


David Currie:

> I am new to D (like many have done C++ , Java ).

Welcome to D :-)
What language do you refer to, D1 or D2? The answers here are about the latest versions of D2.


> Can a class be instantiated on the stack ?

There was a way built in the language to do that (using "scope", it works still but it's deprecated), but now you have to use the std library. See the std.conv.emplace, but keep in mind it has issues (more than the issues of "scope"!) like I think not calling the object destructor.


> It appears that D ASSUMES myC is really a myC*(in C++)

Right, in D class instances are always managed by reference, even when you allocate them on the stack using the emplace trick.


> // but this ALWAYS requires calling the memory allocator
> // this is what Java does (forces your Class instance onto the Heap)

A difference is that the Oracle Java Garbage Collector has a Eden memory for the newly allocated objects that's much faster than the current D GC :-)


> Will a struct do?

Sometimes a struct is enough. D structs are managed by value or by pointer, but they don't support inheritance. In D structs and classes are different (like the memory layout of a class instance is decided by the compiler, while struct fields are in memory as you want them, with the alignment you desire) and they are used for different purposes.


> Does a struct have a constructor (as opposed to an opcall?)

In D2 the struct constructor is this() as for classes.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list