Singleton is a single piece, means that there is only one example in a class in the system. This situation is most common, so Singleton is also the most widely designed design mode (because many design patterns are used to use it too much). However, such as C / * interface definition * / class singleleton {public : Static Singleton * GetInstance (Void); Private: Static Singleton * g_instance; private: Singleton ();
/ * Implementation * / Singleton * Singleton :: i_instance = null; Singleton :: Singleton :: getInstance (void) {if (g_instance == null) {g (g_instance == null) {g_instance = new singleleton ();} return g_Instance ;} / * Then cope with this class: * / int main (void) {Singleton * STN = Singleton :: getInstance (); / * Other code * / delete stn; return 0;} DELETE STN in the main method; As shown: The resource of Singleton :: g_instance must be released by the reference from Singleton - this destroys the independence of class Singleton, and reliability is also affected. So you might want to modify the above code: / * Interface definition * / class singleleton {public: static auto_ptr
/ * Implement * / auto_ptr
STN_PTR STN = Singleton :: getInstance ();
Fun ();
STN-> Method ();
}
As shown above: In C STL, the main scope and the STN in the FUN scope will not proxy one of the same Singleton instance, and each agent a separate Singleton, which is at least destroyed "single mode" , Do not have many words, this impact is very bad.
This is the case:
Singleton :: g_instance is due to the STN variable in assigning the main domain, the pointer it is deprivated by STN (see the assignment operator overload method of Auto_PTR.), So, Singleton :: g_instance is assigned to the STN variable to the FUN domain Have to generate a new Singleton instance.
Of course, all of the AUTO_PTR
You may find a solution around, but all solutions must be implemented around the implementation of the Singleton class or Auto_PTR. According to the reason, more focus is concentrated in Auto_PTR, which is the root cause of the problem. The Auto_PTR method implemented by the Memory header of Microsoft VC 6 avoids the above defects, but the implementation of Auto_PTR in VC7.x is fully referenced from C STL, and "restores this defect". MAIN method results:
In VC 6.x
ctor
Entering fun now ....
Metod Was Called
Leaving fun now ....
Dtor
In vc7.x
CTOR assigns the STN variable to the main domain
Entering fun now ....
CTOR assigns the STN variable in the FUN domain
Method Was Called
Leaving fun now ....
Resources of the pointers of the STN agents in the DTOR sector
Method Was Called
Resources of the pointers of STN agents in the DTOR sector
And if the STN variable type in the main method is changed to Auto_Ptr
ctor
Entering fun now ....
Method Was Called
Leaving fun now ....
Dtor
Method Was caled // mothed method is still valid