Safely moving structs in D
sarn via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jan 23 15:03:53 PST 2017
On Monday, 23 January 2017 at 22:26:58 UTC, bitwise wrote:
> Is it ok to memcpy/memmove a struct in D?
>
> Quote from here:
> https://dlang.org/spec/garbage.html
>
> "Do not have pointers in a struct instance that point back to
> the same instance. The trouble with this is if the instance
> gets moved in memory, the pointer will point back to where it
> came from, with likely disastrous results."
>
> This seems to suggests it's ok to move structs around in memory
> without calling their postblit...but if this is the case, why
> does postblit even exist, if it's not strictly guaranteed to be
> called after the struct has been blitted?
You may need the postblit for a *copying* blit. For example, if
a struct does reference counting, the postblit will need to
increment the count for the new copy. It's a slightly different
solution to what C++ solves with copy constructors, assignment
operators, etc. Compared to C++, the D approach is a bit simpler
and trades off a little flexibility for more opportunities for
the compiler to generate efficient code.
Here's the situation in C++, BTW:
http://en.cppreference.com/w/cpp/language/rule_of_three
More information about the Digitalmars-d-learn
mailing list