D2.0 Stack allocated classes

Kirk McDonald kirklin.mcdonald at gmail.com
Fri Jun 29 17:00:32 PDT 2007


S. wrote:
> Per the memory management whitepaper, the following conditions are
> given for allocating a class on the stack instead of the heap.
> 

The four bullet points must all be true.

> * are allocated as local symbols in a function

As opposed to members of some structure or class, or as global symbols,
or the like.

> * are allocated using new

As opposed to e.g. returned from a function.

> * use new with no argument

If a class overloads the allocator, you can pass additional arguments to
new itself if the allocator accepts them, e.g.:

scope Foo f = new(1, 2, 3) Foo;

If you use this feature, it won't go on the stack.

> * have the scope storage class
> 

Obviously, this is as opposed to /not/ using the scope storage class.

> That covers every way I know how to allocate a class in D.  Maybe is
> poorly written, and I'm confused.  Lists like this are typically used
> to imply that ANY of the conditions being true would cause a stack
> allocation.

No, this list means that ALL of the conditions must be true.

>  If that's not the case, just say:
> 
> "If the class is allocated as a local symbol in a function using new
> with no arguments and has the scope storage class, then it is
> allocated on the stack."
> 

It might be better to say "it may be allocated on the stack," or "the 
implementation is free to allocate it on the stack."

> If I'm not confused, then how do you get something to be allocated on
> the heap?

Foo f = new Foo; // on the heap

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list