emplace

Given a raw memory area chunk (but already typed as a class type T), constructs an object of class type T at that address. The constructor is passed the arguments Args. If T is an inner class whose outer field can be used to access an instance of the enclosing class, then Args must not be empty, and the first member of it must be a valid initializer for that outer field. Correct initialization of this field is essential to access members of the outer class inside T methods. Note: This function is @safe if the corresponding constructor of T is @safe.

Return Value

Type: T

The newly constructed object.

Examples

() @safe {
    class SafeClass
    {
        int x;
        @safe this(int x) { this.x = x; }
    }

    auto buf = new void[__traits(classInstanceSize, SafeClass)];
    auto support = (() @trusted => cast(SafeClass)(buf.ptr))();
    auto safeClass = emplace!SafeClass(support, 5);
    assert(safeClass.x == 5);

    class UnsafeClass
    {
        int x;
        @system this(int x) { this.x = x; }
    }

    auto buf2 = new void[__traits(classInstanceSize, UnsafeClass)];
    auto support2 = (() @trusted => cast(UnsafeClass)(buf2.ptr))();
    static assert(!__traits(compiles, emplace!UnsafeClass(support2, 5)));
    static assert(!__traits(compiles, emplace!UnsafeClass(buf2, 5)));
}();

Meta