Is there any way to make this code work? (combine "Free Lists" and "Explicit Class Instance Allocation")

z z at gg.com
Fri Aug 15 17:36:55 PDT 2008


== Quote from z (z at gg.com)'s article
> Hi,
> I'm reading http://digitalmars.com/d/2.0/memory.html
> and try to combine "Free Lists" and "Explicit Class Instance Allocation".
> So instead of:
> void test()
> {
>     Foo f = Foo.allocate();
>     ...
>     Foo.deallocate(f);
> }
> I can just write as normal:
> void test()
> {
>     Foo f = new Foo();
>     ...
>     delete Foo;
> }
> But the simple code I wrote seg faults. Is this a compiler bug? or I'm doing
> something wrong? or can this thing be done at all?
> Thanks.
>  << custom.d >>

the code:

$ cat custom.d
import std.stdio;
import std.c.stdlib;
import std.outofmemory;
import std.gc;

class Bar {
    public void fun() {
      printf("Bar\n");
    }
}

class Foo : Bar {
    string name;

    this() {
        printf("my ctor\n");
    }

    ~this() {
        printf("my dtor\n");
        // suppose I don't do anything here
    }

    public override void fun() {
        writeln(name);
    }

    new(size_t sz)
    {
        printf("my new\n");
        Foo f;
        if (freelist)
        {   f = freelist;
            freelist = f.next;
            return cast(void*)f;   // I know that ctor will be called again on f.
Is there any way to skip :-) ?
        }

        void* p;
        p = std.c.stdlib.malloc(sz);
        if (!p)
            throw new OutOfMemoryException();
        //std.gc.addRange(p, p + sz);
        return p;
    }

    delete(void* p)
    {
        printf("my del\n");
        // suppose I just save it for reuse, instead of free memory
        Foo f = cast(Foo)p;
        deallocate(f);
        printf("saved!\n");
        // try to call some method, see if it still works:
        f.fun();  // Segmentation fault here. Is there any way to make this work?
        // I run thru the debugger, and found f's attritube is not changed.
        // so what's going wrong?
        // is this because even after I provided my own 'delete' and '~this',
        // compiler still inserted some extra cleanup code?
    }

    static Foo freelist;                // start of free list

    static void deallocate(Foo f)
    {
        f.next = freelist;
        freelist = f;
    }

    Foo next;           // for use by FooFreeList
}

int main() {
  Foo foo;
  foo = new Foo();
  foo.name = "old-guy";
  foo.fun();
  delete foo;

  foo = new Foo();
  foo.fun();

  return 0;
}



More information about the Digitalmars-d mailing list