classes allocated on the stack

Steven Schveighoffer schveiguy at yahoo.com
Thu Apr 24 09:14:49 PDT 2008


Regarding this documentation 
(http://www.digitalmars.com/d/1.0/memory.html#stackclass):

<quote>
Class instances are normally allocated on the garbage collected heap. 
However, if they:

    * are allocated as local symbols in a function
    * are allocated using new
    * use new with no arguments
    * have the scope storage class

then they are allocated on the stack.
</quote>

Why does rule 3 exist?  If I have a class:

class X
{
    private int n;
    this()
    { n = 5; }

    this(int x)
    { initialize(x); }

    initialize(int x)
    { n = x; }
}

And I want to allocate an instance on the stack, with n initialized to 3:

scope x = new X; // allocated on stack
x.initialize(3);
scope x2 = new X(3); // allocated on heap?

What about using the constructor with parameters makes it not possible to 
store on the stack?

-Steve 




More information about the Digitalmars-d-learn mailing list