Search code examples
classobjectheap-memorydstack-memory

Why D doesn't allow object creation on stack?


Consider following program (See live demo here)

import std.stdio;
class myclass
{
    public:
    int get_a()
    {
        return a;
    }
    private:
    int a=3;
}
int main()
{
    myclass m;  // It should be myclass m=new myclass();
    writefln("%d",m.get_a());   
    return 0;
}

C++ supports both automatic (stack allocated) & dynamic (heap allocated) objects. But why every class object must be dynamically allocated in D? Why D doesn't support stack allocated objects?

another surprising thing is that ideone gives compiler error as:

prog.d(14): Error: null dereference in function _Dmain

But when I tried it on my local machine on dmd2 compiler it gives me runtime error not compile time error. Why? Why behaviour of this program is different? Following is the error I've got on my local machine given by dmd2.

object.Error@(0): Access Violation
----------------
0x00402056
0x00405F9B
0x00405EB1
0x00403D93
0x7651EE6C in BaseThreadInitThunk
0x7758377B in RtlInitializeExceptionChain
0x7758374E in RtlInitializeExceptionChain

Solution

  • D does allow placing classes on the stack, see std.typecons.scoped.

    The null dereference error you see on ideone happens because the compiler identified this problem during optimization (ideone seems to enable optimizations). Try adding the -O switch to your local compiler invocation.