Allocating classes on the stack

Lionello Lunesu lio at lunesu.remove.com
Fri Nov 24 04:08:52 PST 2006


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.



More information about the Digitalmars-d-learn mailing list