It's a singleton.
I compile and run it on VC8, it runs OK.
But, I heard my friend he use it before, and there is some problem on it, but he couldn't remember the problem.
Add I test it on static lib and dynamic lib, It runs OK, too.
Indeed, I doubt it, maybe it cann't work in other compiler or other condition that I didn't try. May be some time, the GetInstance() will call the Constructor twice. Or it wasn't inline...
Is there any bug in it?
Could any one help me, Thank you!
As it stands it is too simple - as it uses the compiler provided default constructor, copy constructor, and assignment operator which are public by default - this means that you can create a new one, copy it around and do assignments - whihc all defeats the point of being a 'Singleton'.
You will need to do declarations for these three functions and put them in the private part of the class.
However there is a danger. The name GetInstance does not reflect the implemented definition of the function. In reality, it returns the reference to the same Singleton object which is defined as static inside the function.
The constructor of this static local object will be called only once when the GetInstance function is called for the first time. Run the following code:
// singleton_object.h
class SingletonObject
{
public:
// Get an instance of a singleton class
inlinestatic SingletonObject& GetSingleInstance()
{
static SingletonObject singleton_object;
return singleton_object;
}
private:
// cann't not created out of the class
SingletonObject()
{
cout << "SingletonObject is created" << endl;
}
// without implementation, non copyable.
SingletonObject(const SingletonObject& obj);
// without implementation, non copyable.
SingletonObject& operator=(const SingletonObject& obj);
};
I want the GetSingleInstance() more effective, so I used the keyword inline,
But is "inline" work?
Maybe GetSingleInstance() is not an inline function...
inline says that the function can be resolved anytime it's used. But then you have a SingletonObject each time you call the function. Which is legal but not what you want. But on the other side a function with inline is not necessarily inline
static says that the function is independend of the surrounding class.
So I'd say that inline may be a problem. Check it out