1
Programming / Re: D language - class
« on: February 24, 2015, 08:24:24 PM »Any D language experts here? I want to ask about D's class everywhere I go. Is there a reason why you need to dynamic alloc an instance of a class? What's the problem with this:
MyClass a(1); //this is not possible in D
auto a = new MyClass(1); //this is
Sorry for the necromancy, but as it's not too old, I'll try to
answer it.
In D, as opposed to C++, struct and class are two very different
things. Structs are *always* POD and have value semantics while
classes have reference semantics. This means that you have to
choose you design up-front and think about whether you want
a struct or class. If you need polymorphism, use class. If you
want pass by reference everywhere (probably) use a class, and so
on.
Trying to force a class to a stack allocation can be a pretty
unsafe operation. E.g. If you have the class allocated on the
stack it means it's fixed size. This doesn't play nicely together
with inheritance, and will probably bite you it the ass. It will
also make it easy to pass stack memory to other methods that will
happily assume a class is heap allocated and thus safe to store
a reference to or alias into.
There are ways around this if you know that allocating the class
on the heap using the GC will slow down your program. The (really)
old way was using `scope`, which will probably be deprecated.
Luckily D is powerful enough to provide such fatures in the
library: http://dlang.org/phobos/std_typecons.html#.scoped
This will create a struct and emplace your data in an array.
Again, you're using fixed size memory, so don't try to do any
classish stuff like assigning the variable to another subclass.
In short: structs are PODs located on the stack, classes are
polymorphic types located on the heap.