static variable in function

Started by
11 comments, last by Oberon_Command 8 years, 3 months ago


Consider what happens if RenderManager::GetInstance() is called from somewhere inside of RenderManager's constructor.

Even without the mutex, wouldn't that be likely to be a pretty bad idea?

In the best case, GetInstance would return a half-way constructed RenderManager, in the worst case, it would become an infinite recursion.

Is it even defined in C++ what would happen? (I have no idea, if someone knows, please do tell :) )

I guess the question is, will the return-value from "new" be assigned before or after the constructor is run?

My unqualified guess is "after" which would mean an infinite recursion.

Advertisement

Consider what happens if RenderManager::GetInstance() is called from somewhere inside of RenderManager's constructor.


Even without the mutex, wouldn't that be likely to be a pretty bad idea?
In the best case, GetInstance would return a half-way constructed RenderManager, in the worst case, it would become an infinite recursion.

Is it even defined in C++ what would happen? (I have no idea, if someone knows, please do tell smile.png )
I guess the question is, will the return-value from "new" be assigned before or after the constructor is run?

My unqualified guess is "after" which would mean an infinite recursion.


Yes, you don't want to use this type of singleton and call QInstance inside your constructor. It would work if you had an externally created/destroyed singleton where QInstance only accessed a pointer however.

Though I've personally run into this deadlock problem when someone made the mistake of allocating in the memory manager's constructor. It worked "fine" on platforms that didn't implement thread-safe statics and immediately deadlocked on the one that did implement them. (Cause you redefine new to point at the memory manager, which needs to get the instance...)

Consider what happens if RenderManager::GetInstance() is called from somewhere inside of RenderManager's constructor.


Even without the mutex, wouldn't that be likely to be a pretty bad idea?
In the best case, GetInstance would return a half-way constructed RenderManager, in the worst case, it would become an infinite recursion.


Indeed, but this behaviour apparently reliable enough on some compilers that I've also personally run into this in production code. In fact, the problem was only noticed when switching to a more modern (C++11 friendly) compiler...

This topic is closed to new replies.

Advertisement