Incorporating D

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 25 16:42:50 PST 2013


On Fri, Jan 25, 2013 at 11:32:19PM +0100, Szymon wrote:
> Ah, perfectly clear now. Thanks guys. At one point I though maybe it
> was about move semantics but it indeed about something much more
> fundamental. And indeed surprising coming from C++.
[...]

When moving to D, one thing to keep in mind is that you should not
expect C/C++ struct and D struct to behave the same way, because they do
not.

In D, a struct is a value type, and basically behaves like a glorified
int. This means assignment with = (shallow-)copies the struct, structs
are allocated on the stack by default (unless you explicitly use new),
etc.. Be aware that using struct ctors/dtors is fraught with peril; the
simplest cases do work, but there are some bugs with complicated dtors
and some unexpected behaviour with @disable ctors. If you need a
complicated dtor, chances are you want to be using a class anyway. Same
goes for postblit ctors (the analogue of copy ctors): there are some
bugs related to this, and IMO, if you need to do complicated stuff in a
postblit, you should just use a class.

In D, a class is a reference type, which means they are always passed by
reference, and assignment with = only copies the reference, NOT the
object. By default, they are allocated on the heap (unless you use
emplace), and generally, ctors and dtors work in a much more predictable
and stable way. (But be aware that dtors may not run when you expect,
because the GC may not collect the object immediately after it's out of
use.) Class objects are not deep-copied unless you provide a method to
do that yourself.

In summary, if you want something that behaves like an int, but just
happens to have a couple of extra fields, use a struct. If you want
complex behaviours like ctors, dtors, copy/cloning semantics,
polymorphism, etc., spare yourself the pain and just use a class. (It
*is* possible to pull some tricks along these lines with structs, but
like I said, there is a risk of running into some bugs in that area, so
it's best to steer clear until these issues have been fixed.)


T

-- 
"I suspect the best way to deal with procrastination is to put off the procrastination itself until later. I've been meaning to try this, but haven't gotten around to it yet. " -- swr


More information about the Digitalmars-d mailing list