Force struct allocation on the heap?

John Reimer terminal.node at gmail.com
Sat Oct 18 21:49:53 PDT 2008


Hello Benji,

> Looking at the official docs, I can't find the D1 syntax for forcing a
> struct to be allocated on the heap (so that it can safely be returned
> from a function). I'm pretty sure it's possible (without wrapping the
> struct in a class or an array), but I can't for the life of me
> remember how it's done.
> 
> Thanks for your help!
> 
> --benji
> 


Doesn't this work?

-----------------------------
struct sample { int a; int b; }

auto s = new sample;
-----------------------------

or even the long way, following the example of D custom class allocators 
(from D language manual):

----------------------------
struct sample
{
int a;
int b;
}

sample* p;

p = std.c.stdlib.malloc(sample.sizeof);
if (!p)
throw new OutOfMemoryException();
std.gc.addRange(p, p + sample.sizeof);
----------------------------------------

-JJR




More information about the Digitalmars-d-learn mailing list