November 24, 2006 Allocating classes on the stack | ||||
---|---|---|---|---|
| ||||
The following code works, but is it kosher? #import std.c.stdlib, std.stdio; #template stackAllocator() { # new( size_t size, void* ptr ) { return ptr; } # delete( void* ptr ) { } #} #T stackNew(T)(void* sp =alloca(T.classinfo.init.length) ) { # return new(sp) T; #} #class A { # this() { writefln("this"); } # ~this() { writefln("~this"); } # mixin stackAllocator; #} #void main() { # writefln("{"); # if (1) { # scope auto p = stackNew!(A)(); # writefln("newed"); # } # writefln("}"); #} C:\Users\llunesu\Desktop>dmd -run stack.d { this newed ~this } (It's too bad I can't use "scope class A", since the stackNew is not allowed to return a scoped class) L. |
Copyright © 1999-2021 by the D Language Foundation