Ownership semantics

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 31 12:07:26 PST 2016


On 1/31/16 2:34 PM, maik klein wrote:
> I recently asked a question about ownership semantics in D
> https://stackoverflow.com/questions/35115702/how-do-i-express-ownership-semantics-in-d
>
>
> But a few minutes ago I found an answer on SO that could potentially
> explain a lot.
>
> http://stackoverflow.com/a/35114945/944430
>
> Sadly it has some pseudo code in it so I implemented it with
> std.experimental.allocator
>
> struct UniquePtr(T) {
>      import std.experimental.allocator;
>      private T* ptr = null;
>
>      @disable this(this); // This disables both copy construction and
> opAssign
>
>      this(Args...)(auto ref Args args){
>          ptr = theAllocator.make!T(args);
>      }
>
>      ~this() {
>          theAllocator.dispose(ptr);
>      }
>
>      inout(T)* get() inout {
>          return ptr;
>      }
>
>      // Move operations
>      this(UniquePtr!T that) {
>          this.ptr = that.ptr;
>          that.ptr = null;
>      }
>
>      ref UniquePtr!T opAssign(UniquePtr!T that) { // Notice no "ref" on
> "that"
>          import std.algorithm.mutation;
>          swap(this.ptr, that.ptr); // We change it anyways, because it's
> a temporary
>          return this;
>      }
> }
>
> Is this code correct? One problem that I have is
>
> UniquePtr!int[int] map;
>
> will result in a memory exception and I have no idea why.

The default allocator is the GC.

For memory that is destroyed by the GC, you cannot access to 
GC-allocated members in the destructor (destruction order is not 
guaranteed by the GC). Therefore, you should not 'dispose(ptr)' in the dtor.

What is likely happening is that ptr is already collected, and you are 
invalidly attempting to re-free it.

I'm pretty sure there is no facility in the allocator to give you enough 
information to properly implement this. In other words, for non-GC 
allocators, you *should* dispose the ptr. But how can you tell?

-Steve


More information about the Digitalmars-d-learn mailing list