Hello all,
I have some question about using Signleton class would like to discuss with you guys. When we decide a singleton, sometimes we do this,
Example 1:
class A
{
private :
A();
public :
static A* GetInstance()
{
static A a;
return &a
}
};
This is absolutly good, but when compile in release mode, the compiler will
sometimes make the GetInstance() inline, and it may causes the problem. So, another way to write a singleton class is,
Example 2:
class A
{
private :
static A a;
A();
public:
static A* GetInstance()
{return &a};
};
It work fines even when the compiler change the GetInstance() to inline. But by doing that, we cannot control the order of when the singleton will be created, which is one of the main properties of a singelton class.
Well, some of the solution I know for Exampl 1 is that we enforce the compiler not to change the GetInstance() to be inlined. Which I am not sure how can I do it in Visual .Net. Also, I don't know whether the command to do this is complier dependent. However, personally, I don't think it is a good solution since the function GetInstance() is so simple, and it should be inlined. By enforce the compiler to make it not inline may not be a very good approach.
Another problem of using Singleton is that if the class require some parameters to pass into the constructor, what is the best solution for that?
Also, if I want to do a subclass from a Singleton, what is the best way to do that too?
Thanks!
Edit: added
tags.
<!--EDIT--><span class=editedby><!--/EDIT-->[Edited by - hplus0603 on February 10, 2005 2:04:23 PM]<!--EDIT--></span><!--/EDIT-->