开发者

class with no constructor forces the use of a pointer type?

I don't want to use pointers when I don't have to, but here's the problem: in the code below if I remove the asterisk and make level simply an object, and of course remove the line level = new Level; I get a runtime error, the reason being that level is then initialized on the first line, BEFORE initD3D and init_pipeline - the methods that set up the projection and view for use. You see the problem is that level uses these two things but when done first I get a null pointer exception.

Is this simply a circumstance where the answer is to use a pointer? I've h开发者_高级运维ad this problem before, basically it seems extremely vexing that when a class type accepts no arguments, you are essentially initializing it where you declare it.... or am I wrong about this last part?

Level* level;

D3DMATRIX* matProjection,* matView;

//called once
void Initialise(HWND hWnd)
{
initD3D(hWnd);
    init_pipeline();

level = new Level;
}

I'm coming from c# and in c#, you are simply declaring a name with the line Level level; arguments or not, you still have to initialize it at some point.


You are correct that if you do:

Level level;

then level will be instantiated at that point. That is because the above expression, which appears to be a global, isn't just a declaration, but also a definition.

If this is causing you problems because Level is being instantiated before something else is being instantiated, then you have encountered a classic reason why globals suck.

You have attempted to resolve this by making level a pointer and then "initializing" it later. Wjhat might suprise you is that level is still being instantiated at the same point. The difference now is the type of level. It's not a Level anymore; now its a pointer-to-level. If you examine the value of level when your code enters Initialize you'll see that it has a value of NULL.

It has a value of NULL instead of a garbage value because globals are static initialized, which in the case here, means zero-initialized.

But this is all somewhat tangential to the real problem, which is that you are using globals in the first place. If you need to instantiate objects in a specific order, then instantiate them in that order. Don't use globals, and you may find that by doing that, you don't need to use pointers, either.


Is this simply a circumstance where the answer is to use a pointer

Yea, basically.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜