Classes on stack

Redwan rdwnsjjd at gmail.com
Thu Sep 1 18:50:05 UTC 2022


On Thursday, 1 September 2022 at 18:26:12 UTC, Ali Çehreli wrote:
> On 9/1/22 10:59, Redwan wrote:
>> On Thursday, 1 September 2022 at 13:53:06 UTC, IGotD- wrote:
>
>>> If you have any classes in the class you allocate on the 
>>> stack, the constructor of the class will allocate them on the 
>>> heap. Basically only the top level class will be on stack.
>> 
>> Can you give an example?
>> 
>
> Sorry to jump in but the following program demonstrates this by 
> pointer values:
>
> import std.stdio;
>
> class A {
>   int i;
> }
>
> class B {
>   A a;
>   int i;
>
>   this() {
>     this.a = new A();
>   }
> }
>
> void main() {
>   scope b = new B();
>   int i;
>
>   writeln("on stack: ", &i);
>   writeln("on stack: ", &b.i);
>   writeln("on heap : ", &b.a.i);
> }
>
> Ali

how about `scope this.a = new A();`?


More information about the Digitalmars-d mailing list