class CMyClass : ..., public CComCoClass< ... >
{
public:
DECLARE_CLASSFACTORY_SINGLETON(CMyClass)
...
};
另外在MSDN中
有一篇“HOWTO: Alternative Implementation of ATL Singleton”
提供了另外一种替代的方法
This article shows an implementation of singletons that differs from the default ATL implementation in the following ways:
The lifetime of an ATL singleton is tied to the class factory; the singleton gets destroyed only when the class factory is destroyed, which is when the EXE/DLL unloads [CComModule::RevokeClassObject() and CComModule::Term()]. The singleton implementation in this article maintains a refcount and deletes itself when it goes to zero.
Implementing singletons in a DLL can be problematic. One scenario is if your singleton object marked "Apartment", is in a DLL. The client creates two STA threads, each one creates your singleton object. Both STA threads have the same raw pointer to your singleton, allowing them to simultaneously call into the singleton. You are probably not synchronizing access to instance data in your singleton object, because according to COM rules, you don't need to synchronize access to instance data for objects marked "Apartment". It's only a matter of time before data is corrupted.
The singleton implementation in this article works around this problem by returning a marshaled pointer in IClassFactory::CreateInstance(). But marshaling the pointer introduces another potential problem. All calls are now marshaled to the first Apartment that calls IClassFactory::CreateInstance. If the first Apartment goes away, calls to the singleton from other Apartments will fail. If you use the singleton implementation in this article in a DLL marked "Apartment", you must ensure that the first Apartment that uses the component stays alive. Because of all these potential problems, you should only use singletons in a DLL when absolutely necessary. If you just want to share data in the DLL within the same process, an alternative is to create global/static variables to hold the data. You just need to synchronize access to this data.