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.

Template std.typecons.scoped

Allocates a class object right inside the current scope, therefore avoiding the overhead of new. This facility is unsafe; it is the responsibility of the user to not escape a reference to the object outside the scope.

Arguments

template scoped(T);

Functions

Function name Description
scoped

Note

it's illegal to move a class reference even if you are sure there are no pointers to it. As such, it is illegal to move a scoped object.

Example

class A
{
    int x;
    this()     {x = 0;}
    this(int i){x = i;}
}

// Standard usage
auto a1 = scoped!A();
auto a2 = scoped!A(1);
a1.x = 42;
assert(a1.x == 42);
assert(a2.x ==  1);

// Restrictions
static assert(!is(typeof({
    auto e1 = a1; // illegal, scoped objects can't be copied
    assert([a2][0].x == 42); // ditto
    alias ScopedObject = typeof(a1);
    auto e2 = ScopedObject();  //Illegal, must be built via scoped!A
    auto e3 = ScopedObject(1); //Illegal, must be built via scoped!A
})));

// Use as member variable
struct B
{
    typeof(scoped!A()) a; // note the trailing parentheses
}

// Use with alias
alias makeScopedA = scoped!A;
auto a6 = makeScopedA();
auto a7 = makeScopedA();

Authors

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

License

Boost License 1.0.

Comments