Delay allocating class instance in stack.
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 21 01:46:43 PDT 2017
On 03/21/2017 01:08 AM, ANtlord wrote:
> void method(bool flag) @nogc
> {
> scope MyClass obj;
> if(flag) {
> obj = new MyClass(1);
> } else {
> obj = new MyClass(2);
> }
> // using obj
> }
Another option is std.conv.emplace:
import std.conv : emplace;
class MyClass {
this(int) @nogc {
}
~this() @nogc {
}
}
void method(bool flag) @nogc
{
void[__traits(classInstanceSize, MyClass)] buffer = void;
MyClass obj;
if(flag) {
obj = emplace!MyClass(buffer, 1);
} else {
obj = emplace!MyClass(buffer, 2);
}
// Unfortunately, destroy() is not @nogc
// scope(exit) destroy(obj);
}
void main() {
method(false);
method(true);
}
Ali
More information about the Digitalmars-d-learn
mailing list