www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - 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.
Nov 24 2006