Incorporating D

Dmitry Olshansky dmitry.olsh at gmail.com
Sat Jan 26 00:14:09 PST 2013


26-Jan-2013 04:42, H. S. Teoh пишет:
> 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 general postblit/dtor are working but I wouldn't recommend using them 
in complex code (least you want to file a bug report) like with 
statements, or array-literals [ Struct(...), Struct(...), Struct(...)], 
and of course built-in associative arrays(!).

Another thing of importance is that pass-by-value is automated to move 
(simple bitwise-copy) where applicable as D structs can't have internal 
references. And you don't have to define move constructor or rely on 
sombody to define it.

>
> 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
>


-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list