Description of an alternative implementation of ATL singleton in Visual C++ 6.0 (201321)
The information in this article applies to:
- The Microsoft Active Template Library (ATL) 3.0, when used with:
- Microsoft Visual C++, 32-bit Enterprise Edition 6.0
- Microsoft Visual C++, 32-bit Professional Edition 6.0
- Microsoft Visual C++, 32-bit Learning Edition 6.0
This article was previously published under Q201321 SUMMARY 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.
REFERENCES (c) Microsoft Corporation 1999, All Rights Reserved.
Contributions by Samson Tanrena, Microsoft Corporation.
Modification Type: | Minor | Last Reviewed: | 5/3/2005 |
---|
Keywords: | kbinfo kbArchitecture kbhowto KB201321 kbAudDeveloper |
---|
|