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

1 () @safe {
2     class SafeClass
3     {
4         int x;
5         @safe this(int x) { this.x = x; }
6     }
7 
8     auto buf = new void[__traits(classInstanceSize, SafeClass)];
9     auto support = (() @trusted => cast(SafeClass)(buf.ptr))();
10     auto safeClass = emplace!SafeClass(support, 5);
11     assert(safeClass.x == 5);
12 
13     class UnsafeClass
14     {
15         int x;
16         @system this(int x) { this.x = x; }
17     }
18 
19     auto buf2 = new void[__traits(classInstanceSize, UnsafeClass)];
20     auto support2 = (() @trusted => cast(UnsafeClass)(buf2.ptr))();
21     static assert(!__traits(compiles, emplace!UnsafeClass(support2, 5)));
22     static assert(!__traits(compiles, emplace!UnsafeClass(buf2, 5)));
23 }();

Meta

Suggestion Box / Bug Report