Thanks in advance!
Referring to Effective c++ item 4, Scott Meyers said all static variable/instance will be destroyed once main() exit. Here, we assume the singleton is only used in main().
Indeed, we know that if we use both two following forms of singleton, the instance will be destroyed automatically once the main() exit. But I want to distinguish two reasons below, which one is the direct reason to free the singleton? BTW, what is the difference between this two forms?
Reason:
-
normal instance will be destroyed once main() exit. (Not related to static)
-
all static variable/instance will be destroyed once main() exit.
case 1:
//Singleton.h
class Singleton
{
private:
Singleton();
~Singleton();
public:
Singleton& Instance()
{
Return instance_;
}
static Singleton instance_;
};
//Singleton.c
Singleton Singleton::instance_
Instance destruction step:
- Referring to Effective c++ item 4, static instance_ will be free by compiler. This form seems related to reason 2.
case 2:
//Singleton.h
class Singleton
{
private:
Singleton();
~Singleton();
public:
Singleton& Instance()
{
static Singleton instance_;
Return instance_;
}
};
Instance destruction step:
-
The singleton 's destructor is called once program exit.
-
Then the desctrutor will free all the member, including the static member, instance_. Even though instance_ is not static, it will be free, either. This form seems related to reason 1.
Aucun commentaire:
Enregistrer un commentaire