Relocatable objects and internal pointers

Matt Elkins via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 29 17:49:30 PST 2016


On Saturday, 30 January 2016 at 01:28:54 UTC, H. S. Teoh wrote:
> 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

Yeah, but the whole point of what I am doing is to avoid using 
the heap; I can think of several ways to implement this if I 
relax that restriction :). I'm basically trying to make C++'s 
std::unique_ptr for resource handles, a thin wrapper which 
ensures resource cleanup and allows moving the handle. Since I'm 
putting it in my lowest-level/most-generic library with no 
visibility on how it gets used, I want it very lightweight 
(ideally zero-cost, like I can do in C++11, or at least low-cost 
[sans heap] like I could do in C++98) so that I can use it with 
the broadest range of higher-level applications.


More information about the Digitalmars-d-learn mailing list