Classes on stack
mw
mingwu at gmail.com
Thu Sep 1 19:07:44 UTC 2022
On Thursday, 1 September 2022 at 18:50:05 UTC, Redwan wrote:
> 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();`?
It won't compile:
onlineapp.d(21): Error: found `=` instead of statement
try it online here:
https://run.dlang.io/
More information about the Digitalmars-d
mailing list