开发者

Error: null dereference

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开发者_StackOverflow中文版 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 a null pointer, and have not, in fact, created an object. An object must be created using the new operator:

auto obj = new Object();

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:

scope obj = new MyObject;

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:

int main(string[] args)
{
    ...
}

char[] and string have the same physical layout, but mean slightly different things; specifically, string is just an alias for immutable(char)[], so by using char[] you're circumventing the const system protections.


I don't read your code all that well since I'm a VB guy, but it looks like you're initiating an object without it having a value.

You create an object called obj You call obj.x then you return "0" (zero)

what exactly are you doing? I'm pretty sure obj needs to be NEW, and you need to be returning something other than a physical "0"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜