struct vs class

bearophile bearophileHUGS at
Sun Nov 14 03:49:03 PST 2010


> a value makes no sense by itself, it is bound to what it describes an aspect of; referencing a value is meaningless, only copy makes no sense. For instance, the position & color of a visual form should be values.

Structs may have a meaning by themselves, all kind of member functions, and you may manage structs by pointer.

> Struct instances have fast creation, because allocated on the stack (*)?

You may allocate them on the heap too, with "new". And if you put a struct inside an object instance, among its fields, then the struct is allocated where the class instance is allocated, generally (but not always) on the heap. Structs may also be allocated in the static section, like static variable, and as global constant too.

> Class instances are costly to create. But then, passing class instances around is light, since only a reference is copied, while struct instances are copied at the field level.

But structs may also be passed around by ref, and by pointer.

> What kinds should be Node & Tree? Why? Are there sensible alternatives? If yes, what are the advantages and drawback of each? In what cases?

If efficiency is not so strong, then using classes is the simpler solution. Otherwise you want to use structs plus various kinds of C hacks.

> (*) Is this true? And why is the stack more efficient than the heap?

In Java the GC keeps the objects in separated groups, the first generation is managed as a stack, so allocation is almost as fast as stack allocation. But current D GC is more primitive, it uses a more complex allocation scheme that requires more time. Allocation on a stack is easy, you ideally only need to increment an index/pointer...


More information about the Digitalmars-d-learn mailing list