Ownership semantics
maik klein via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jan 31 11:34:43 PST 2016
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.
More information about the Digitalmars-d-learn
mailing list