On Monday, 20 April 2015 at 21:36:35 UTC, Ali Çehreli wrote:
final class Foo {
    uint id;

    @nogc
    this(uint id) {
        this.id = id;
    }
}

C reuse(C, T...)(ref C old, T ctorParams)
{
    import std.conv;
    import std.typetuple;

    enum objectSize = __traits(classInstanceSize, C);

    void* oldPlace = cast(void*)old;

It's probably better to call the destructor here before calling emplace, to complete the lifecycle of the old object.

C newObject = emplace!C(oldPlace[0..objectSize], ctorParams);

    old = null;

    return newObject;
}

void main()
{
    Foo f = new Foo(42);

    auto f2 = f.reuse(43);

    assert(f is null);
    assert(f2.id == 43);
}

Ali

Reply via email to