View source code Display the source code in std/typecons.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Struct std.typecons.Unique

Encapsulates unique ownership of a resource. Resource of type T is deleted at the end of the scope, unless it is transferred. The transfer can be explicit, by calling release, or implicit, when returning Unique from a function. The resource can be a polymorphic class object, in which case Unique behaves polymorphically too.

Constructors

Name Description
this 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 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.

Properties

Name Type Description
isEmpty [get] bool Returns whether the resource exists.

Methods

Name Description
opDot Forwards member access to contents.
release Transfer ownership to a Unique rvalue. Nullifies the current contents.

Templates

Name Description
opAssign Transfer ownership from a Unique of a type that is convertible to our type.
this Constructor that takes a Unique of a type that is convertible to our type.

Example

static 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();
increment(u1);
assert(u1.i == 6);
//consume(u1); // Error: u1 is not copyable
// Transfer ownership of the resource
consume(u1.release);
assert(u1.isEmpty);

Authors

Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara

License

Boost License 1.0.

Comments