Relocatable objects and internal pointers
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 29 17:28:54 PST 2016
On Sat, Jan 30, 2016 at 01:21:27AM +0000, Matt Elkins via Digitalmars-d-learn wrote:
> On Saturday, 30 January 2016 at 01:18:33 UTC, Ali Çehreli wrote:
> >Definitely so. Rvalues are moved around all the time. The following
> >program has two rvalue moves without calling post-blits or
> >destructors.
>
> Oi, that makes life tough. Ok, I'll figure something else out, then...
[...]
Keep in mind that D structs are conceptually different from C++ structs
(even if they are similarly implemented). D structs are supposed to be
value types with POD-like semantics; so when passing structs around they
are bit-copied into the destination and then the postblit method
(this(this)) is called to "patch up" the copy. This is unlike in C++
where you have copy ctors and dtors and operator=() to manage copying.
Because there are no copy ctors, having internal pointers can be
dangerous, since structs can move around in memory without any warning
(e.g., returning a struct from a function generally involves copying it
from the callee's stack frame into a local variable in the caller's
stack frame).
If you need something with internal pointers, you might want to consider
classes instead. Either that, or be sure to allocate your structs on the
heap instead, and work with pointers instead of the struct values
directly. (Note that this is still risky, since somebody might
dereference the pointer and get a stack copy of the struct, which will
cause problems when it then gets passed around.)
T
--
I am a consultant. My job is to make your job redundant. -- Mr Tom
More information about the Digitalmars-d-learn
mailing list