Copy Constructors, Move Semantics and Lifetime
34.1 Copy Constructors (Replacing Postblit)
Postblit (this(this)) is the legacy mechanism. Prefer copy constructors.
struct Buffer
{
int[] data;
this(ref return scope const Buffer rhs) // copy constructor
{
data = rhs.data.dup; // deep copy
}
@disable this(this); // old-style postblit disabled (optional)
}34.2 Move Semantics
Rvalues are moved by default (D structs are assumed movable: no internal self-pointers).
Move constructors (this(Foo rhs) as a move constructor) are in progress in newer compilers. Check the changelog.
import core.lifetime : move, moveEmplace, forward;
struct Unique { int* p; @disable this(this); ~this() { /* free p */ } }
Unique a = Unique(new int(5));
Unique b = move(a); // a is reset to .init; ownership transferred
void consume(Unique u) {}
consume(move(b)); // rvalues are moved automatically
auto wrapper(Args...)(auto ref Args args) { return target(forward!args); } // perfect forwarding34.3 Lifetime Hooks Summary
this(ref return scope T rhs) Destruction (deterministic for structs) @disable this(); Force explicit construction
@disable this(this); / @disable this(ref T)