Unique

Encapsulates unique ownership of a resource.

When a Unique!T goes out of scope it will call destroy on the resource T that it manages, unless it is transferred. One important consequence of destroy is that it will call the destructor of the resource T. GC-managed references are not guaranteed to be valid during a destructor call, but other members of T, such as file handles or pointers to malloc memory, will still be valid during the destructor call. This allows the resource T to deallocate or clean up any non-GC resources.

If it is desirable to persist a Unique!T outside of its original scope, then it can be transferred. The transfer can be explicit, by calling release, or implicit, when returning Unique from a function. The resource T can be a polymorphic class object or instance of an interface, in which case Unique behaves polymorphically too.

If T is a value type, then Unique!T will be implemented as a reference to a T.

Constructors

this
this(RefT p)

Constructor that takes an rvalue. It will ensure uniqueness, as long as the rvalue isn't just a view on an lvalue (e.g., a cast). Typical usage:

this
this(RefT p)

Constructor that takes an lvalue. It nulls its source. The nulling will ensure uniqueness as long as there are no previous aliases to the source.

this
this(Unique!U u)

Constructor that takes a Unique of a type that is convertible to our type.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Postblit

this(this)
this(this)

Postblit operator is undefined to prevent the cloning of Unique objects.

Members

Aliases

RefT
alias RefT = T

Represents a reference to T. Resolves to T* if T is a value type.

Functions

opAssign
void opAssign(Unique!U u)

Transfer ownership from a Unique of a type that is convertible to our type.

release
Unique release()

Transfer ownership to a Unique rvalue. Nullifies the current contents. Same as calling std.algorithm.move on it.

Mixins

__anonymous
mixin Proxy!_p

Forwards member access to contents.

Properties

isEmpty
bool isEmpty [@property getter]

Returns whether the resource exists.

Static functions

create
Unique!T create(A args)

Allows safe construction of Unique. It creates the resource and guarantees unique ownership of it (unless T publishes aliases of this). Note: Nested structs/classes cannot be created.

Examples

struct S
{
    int i;
    this(int i){this.i = i;}
}
Unique!S produce()
{
    // Construct a unique instance of S on the heap
    Unique!S ut = new S(5);
    // Implicit transfer of ownership
    return ut;
}
// Borrow a unique resource by ref
void increment(ref Unique!S ur)
{
    ur.i++;
}
void consume(Unique!S u2)
{
    assert(u2.i == 6);
    // Resource automatically deleted here
}
Unique!S u1;
assert(u1.isEmpty);
u1 = produce();
assert(u1.i == 5);
increment(u1);
assert(u1.i == 6);
//consume(u1); // Error: u1 is not copyable
// Transfer ownership of the resource
consume(u1.release);
assert(u1.isEmpty);

Meta