This code:
int main(char[][] args)
{
MyObject obj;
obj.x;
return 0;
}
gives me: Error: null dereference in function _Dmain when I compile it with -O flag (on dmd2) Why? Isn’t obj allocated on the stack? Should I always use new to create objects?
Summary: you have to new objects. Always.
D’s classes are closer to C# or Java than C++. Specifically, objects are always, always reference values.
MyObject is, under the hood, a pointer to the actual object. Thus, when you use
MyObject obj;, you’re creating anullpointer, and have not, in fact, created an object. An object must be created using thenewoperator:This creates obj on the heap.
You cannot directly construct objects on the stack in D. The best you can do is something like this:
The compiler is allowed to place the object on the stack, but doesn’t have to.
(Actually, I suspect this might be going away in a future version of D2.)
On a side note, if you are using D2, then I believe your main function should look like this:
char[]andstringhave the same physical layout, but mean slightly different things; specifically,stringis just an alias forimmutable(char)[], so by usingchar[]you’re circumventing the const system protections.