Destruction of singleton in DLL - c++

I’m trying to create a simple Win32 DLL. As interface between DLL and EXE I use C functions, but inside of DLL i use C++ singleton object. Following is an example of my DLL implementation:
// MyDLLInterface.cpp file --------------------
#include "stdafx.h"
#include <memory>
#include "MyDLLInterface.h"
class MySingleton
{
friend class std::auto_ptr< MySingleton >;
static std::auto_ptr< MySingleton > m_pInstance;
MySingleton()
{
m_pName = new char[32];
strcpy(m_pName, “MySingleton”);
}
virtual ~ MySingleton()
{
delete [] m_pName;
}
MySingleton(const MySingleton&);
MySingleton& operator=(const MySingleton&);
public:
static MySingleton* Instance()
{
if (!m_pInstance.get())
m_pInstance.reset(new MySingleton);
return m_pInstance.get();
}
static void Delete()
{
m_pInstance.reset(0);
}
void Function() {}
private:
char* m_pName;
};
std::auto_ptr<MySingleton> MySingleton::m_pInstance(0);
void MyInterfaceFunction()
{
MySingleton::Instance()->Function();
}
void MyInterfaceUninitialize()
{
MySingleton::Delete();
}
// MyDLLInterface.h file --------------------
#if defined(MY_DLL)
#define MY_DLL_EXPORT __declspec(dllexport)
#else
#define MY_DLL_EXPORT __declspec(dllimport)
#endif
MY_DLL_EXPORT void MyInterfaceFunction();
MY_DLL_EXPORT void MyInterfaceUninitialize();
The problem or the question that i have is following: If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening? It looks like the destruction off MySingleton happens after EXEs exit. Is it possible to force the DLL or EXE to destroy the MySingleton a little bit earlier, so I don't need to call MyInterfaceUninitialize() function?
EDIT:
Thanks for all your help and explanation. Now i understand that this is a design issue. If i want to stay with my current solution, i need to call MyInterfaceUninitialize() function in my EXE. If i don't do it, it also OK, because the singleton destroys itself, when it leaves the EXE scope (but i need to live with disturbing debugger messages). The only way to avoid this behavior, is to rethink the whole implementation.
I can also set my DLL as "Delay Loaded DLLs" under Linker->Input in Visual Studio, to get rid of disturbing debugger messages.

If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening?
This is not a leak, this is the way auto_ptrs are supposed to work. They release the instance when they go out of scope (which in your case is when the dll is unloaded).
It looks like the destruction off MySingleton happens after EXEs exit.
Yes.
Is it possible to force the DLL or EXE to destroy the MySingleton a little bit earlier, so I don't need to call MyInterfaceUninitialize() function?
Not without calling this function.

You can take advantage of the DllMain callback function to take appropriate action when the DLL is loaded/unloaded or a process/thread attaches/detaches. You could then allocate objects per attached process/thread instead of using a singleton since this callback function is executed in the context of the attached thread. With that in mind, also take a look at Thread Local Storage (TLS).

Honestly, for the example you gave, it doesn't matter if you call the Uninitialize method from your ExitInstance. Yes, the debugger will complain about the unreleased memory, but then again, it's a singleton, it's intended to live for an extended duration.
Only if you have some state information in the DLL that needs to be persisted at exit, or if you are dynamically loading/unloading DLLs multiple times, do you need to be diligent about cleaning up. Otherwise, just letting the OS tear down the process at exit is just fine, the reported memory leak is inconsequential at that point.

Related

How to delete singleton instance from separate module before system killed running threads

I have a C++ Windows (compiled with Visual Studio 2019) program that uses shared libraries. A shared library uses a singleton on a class that creates a thread. The class destructor kills the thread cleanly, so there should be no memory leak. However, I see that the destructor is being invoked after the system actually killed all running threads upon exit, so it's too late, the thread is not exited cleanly and this introduces a memory leak (and possibly other problems depending on the code being processed by the thread).
Here is a MCVE:
#include <thread>
#include <atomic>
class Single
{
public:
static Single& GetInstance()
{
static Single single;
return single;
}
int doSomething()
{
while ( !started )
std::this_thread::sleep_for( std::chrono::milliseconds(100) );
return 0;
}
private:
Single() :
started( false ),
continueThread( true )
{
thread = new std::thread( &Single::threadFunc, this );
}
~Single()
{
continueThread = false;
thread->join();
delete thread;
}
void threadFunc()
{
started = true;
while ( continueThread )
{
std::this_thread::sleep_for( std::chrono::milliseconds(1) );
}
}
std::atomic_bool started;
std::atomic_bool continueThread;
std::thread* thread;
};
int main( int argc, char* argv[] )
{
return Single::GetInstance().doSomething();
}
If this is copied to a single main.cpp file and executed, everything works fine. When ~Single is executed, in the debugger, I see the threadFunc thread is running and it gets stopped cleanly.
Now, if Single definition and implementation is moved to a separate dll. When ~Single is executed, in the debugger, I see the threadFunc thread is not running anymore (the system already stopped it) and the code can't stop in cleanly. Visual Leak Detector reports then a memory leak.
Is there any flag (in code or at compiler level) that could be set to guarantee threads are not destroyed before the singleton gets deleted?
I know I could call a deinit function manually from the main function, but at some point, the main may not even know there is singleton running a thread in the shared library it uses...the shared library itself should be able to cleanly exit.
No.
Multithreading, automatic cleanup, and DLL unloading are basically a huge mess on Windows once they interact.
The solution is to not have singletons, or any static lifetime variables (globals, local statics, class statics) with non-trivial destruction semantics. Make an instance of your thing in main()/WinMain(). Pass a reference to whoever needs it. Let the destructor clean it up before main exits and thus before everything gets unloaded.
Or simply ignore the memory leak. The process is exiting anyway.
This a common case of SUOF (Static Unitialization Order Fiasco) caused by giving up control over object instance lifetime by using static local variable. Solution is to get back control over object instance lifetime by adding a couple of initialization / uninitialization routines (probably wrapped with RAII) that will ensure that object is created before the first use and destroyed after last use but prior to dll getting unloaded / main function returning.

Segfault After Registering Callback Functions

I am registering four callback functions:
glfwSetMouseButtonCallback(procMouseButton);
glfwSetMousePosCallback(procMousePosition);
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
Each callback function looks similar to this:
void GLFWCALL procMouseButton(int button, int action) {
Input::instance().processMouseButton(button, action); // doesn't do anything yet
}
Input is a singleton:
Input& Input::instance()
{
static Input instance;
return instance;
}
After the callback functions are registered, a segfault occurs. I have narrowed down the problem to two things.
First: Excluding any of the process functions causes the segfault to disappear. For example,
// this works
glfwSetMouseButtonCallback(procMouseButton);
//glfwSetMousePosCallback(procMousePosition);
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
// this works also
glfwSetMouseButtonCallback(procMouseButton);
glfwSetMousePosCallback(procMouseButton); // exclude procMousePosition
glfwSetCharCallback(procCharInput);
glfwSetKeyCallback(procKeyInput);
Second: Segfault occurs when popping or pushing a std::vector declared here in singleton Engine:
class Engine
{
public:
static Engine& instance();
std::list<GameState*> states;
private:
Engine() {}
Engine(Engine const& copy);
Engine& operator=(Engine const& copy);
};
// either causes segfault after registering functions
Engine::instance().states.push_back(NULL);
Engine::instance().states.pop_front();
I am completely baffled. I am assuming the problem is related to static initialization order fiasco, but I have no idea how to fix it. Can anyone explain why this error is occurring?
Important notes:
If I reverse the linking order, it no longer segfaults.
I am using MinGW/GCC for compiling.
I am running single threaded.
The singletons do not have default constructors, everything is initialized by Singleton::instance().initialize();
The exact segfault call stack:
0047B487 std::__detail::_List_node_base::_M_hook(std::__detail::_List_node_base*) ()
00000000 0x00401deb in std::list >::_M_insert()
00000000 0x00401dbb in std::list >::push_back()
00401D92 Engine::pushState(GameState*) ()
00404710 StartupState::initialize() ()
00402A11 Engine::initialize() ()
00000000 0x00403f29 in main()
Without seeing the rest of your program, it's hard to say why it's segfaulting. It sounds timing-related. Here's a few things you can try:
Put breakpoints in the constructors of your Engine class, Input class, (any other involved classes,) and the callback-setting code. That will tell you if the callbacks are registering before the singletons they use construct. Note that breakpoints might throw off your program's timing, so if one class hits first, you can disable that breakpoint and rerun. Try this multiple times to check the results are consistent.
Is there a reason you can't try the change to pointers instead of references (like the "fiasco" mentions)?
(Your update while I was writing this makes this part not-so-useful since the callstack shows it's not in a constructor. )This sounds like the callbacks are registering during construction of some class. If that's the case:
Can you move the registration calls so they happen under main()? That ought to get you past initializations.
Split up the class construction into two phases: the normal constructor, and an init() function. Put the critical code inside init(), and call that after everybody has finished constructing.
You could also prevent the callbacks from happening until later. If you can't move the callback registration to a later time in your game's startup, you could put flags so they don't do anything until a "safe" time. Adjusting when this flag enables could let you see "how late" is "late enough". The extra if() overhead is better than a crash. :)
volatile bool s_bCallbackSafe = false; // set this at some point in your game/app
void GLFWCALL procMouseButton(int button, int action) {
if (s_bCallbackSafe)
Input::instance().processMouseButton(button, action); // doesn't do anything yet
}

How can I schedule some code to run after all '_atexit()' functions are completed

I'm writing a memory tracking system and the only problem I've actually run into is that when the application exits, any static/global classes that didn't allocate in their constructor, but are deallocating in their deconstructor are deallocating after my memory tracking stuff has reported the allocated data as a leak.
As far as I can tell, the only way for me to properly solve this would be to either force the placement of the memory tracker's _atexit callback at the head of the stack (so that it is called last) or have it execute after the entire _atexit stack has been unwound. Is it actually possible to implement either of these solutions, or is there another solution that I have overlooked.
Edit:
I'm working on/developing for Windows XP and compiling with VS2005.
I've finally figured out how to do this under Windows/Visual Studio. Looking through the crt startup function again (specifically where it calls the initializers for globals), I noticed that it was simply running "function pointers" that were contained between certain segments. So with just a little bit of knowledge on how the linker works, I came up with this:
#include <iostream>
using std::cout;
using std::endl;
// Typedef for the function pointer
typedef void (*_PVFV)(void);
// Our various functions/classes that are going to log the application startup/exit
struct TestClass
{
int m_instanceID;
TestClass(int instanceID) : m_instanceID(instanceID) { cout << " Creating TestClass: " << m_instanceID << endl; }
~TestClass() {cout << " Destroying TestClass: " << m_instanceID << endl; }
};
static int InitInt(const char *ptr) { cout << " Initializing Variable: " << ptr << endl; return 42; }
static void LastOnExitFunc() { puts("Called " __FUNCTION__ "();"); }
static void CInit() { puts("Called " __FUNCTION__ "();"); atexit(&LastOnExitFunc); }
static void CppInit() { puts("Called " __FUNCTION__ "();"); }
// our variables to be intialized
extern "C" { static int testCVar1 = InitInt("testCVar1"); }
static TestClass testClassInstance1(1);
static int testCppVar1 = InitInt("testCppVar1");
// Define where our segment names
#define SEGMENT_C_INIT ".CRT$XIM"
#define SEGMENT_CPP_INIT ".CRT$XCM"
// Build our various function tables and insert them into the correct segments.
#pragma data_seg(SEGMENT_C_INIT)
#pragma data_seg(SEGMENT_CPP_INIT)
#pragma data_seg() // Switch back to the default segment
// Call create our call function pointer arrays and place them in the segments created above
#define SEG_ALLOCATE(SEGMENT) __declspec(allocate(SEGMENT))
SEG_ALLOCATE(SEGMENT_C_INIT) _PVFV c_init_funcs[] = { &CInit };
SEG_ALLOCATE(SEGMENT_CPP_INIT) _PVFV cpp_init_funcs[] = { &CppInit };
// Some more variables just to show that declaration order isn't affecting anything
extern "C" { static int testCVar2 = InitInt("testCVar2"); }
static TestClass testClassInstance2(2);
static int testCppVar2 = InitInt("testCppVar2");
// Main function which prints itself just so we can see where the app actually enters
void main()
{
cout << " Entered Main()!" << endl;
}
which outputs:
Called CInit();
Called CppInit();
Initializing Variable: testCVar1
Creating TestClass: 1
Initializing Variable: testCppVar1
Initializing Variable: testCVar2
Creating TestClass: 2
Initializing Variable: testCppVar2
Entered Main()!
Destroying TestClass: 2
Destroying TestClass: 1
Called LastOnExitFunc();
This works due to the way MS have written their runtime library. Basically, they've setup the following variables in the data segments:
(although this info is copyright I believe this is fair use as it doesn't devalue the original and IS only here for reference)
extern _CRTALLOC(".CRT$XIA") _PIFV __xi_a[];
extern _CRTALLOC(".CRT$XIZ") _PIFV __xi_z[]; /* C initializers */
extern _CRTALLOC(".CRT$XCA") _PVFV __xc_a[];
extern _CRTALLOC(".CRT$XCZ") _PVFV __xc_z[]; /* C++ initializers */
extern _CRTALLOC(".CRT$XPA") _PVFV __xp_a[];
extern _CRTALLOC(".CRT$XPZ") _PVFV __xp_z[]; /* C pre-terminators */
extern _CRTALLOC(".CRT$XTA") _PVFV __xt_a[];
extern _CRTALLOC(".CRT$XTZ") _PVFV __xt_z[]; /* C terminators */
On initialization, the program simply iterates from '__xN_a' to '__xN_z' (where N is {i,c,p,t}) and calls any non null pointers it finds. If we just insert our own segment in between the segments '.CRT$XnA' and '.CRT$XnZ' (where, once again n is {I,C,P,T}), it will be called along with everything else that normally gets called.
The linker simply joins up the segments in alphabetical order. This makes it extremely simple to select when our functions should be called. If you have a look in defsects.inc (found under $(VS_DIR)\VC\crt\src\) you can see that MS have placed all the "user" initialization functions (that is, the ones that initialize globals in your code) in segments ending with 'U'. This means that we just need to place our initializers in a segment earlier than 'U' and they will be called before any other initializers.
You must be really careful not to use any functionality that isn't initialized until after your selected placement of the function pointers (frankly, I'd recommend you just use .CRT$XCT that way its only your code that hasn't been initialized. I'm not sure what will happen if you've linked with standard 'C' code, you may have to place it in the .CRT$XIT block in that case).
One thing I did discover was that the "pre-terminators" and "terminators" aren't actually stored in the executable if you link against the DLL versions of the runtime library. Due to this, you can't really use them as a general solution. Instead, the way I made it run my specific function as the last "user" function was to simply call atexit() within the 'C initializers', this way, no other function could have been added to the stack (which will be called in the reverse order to which functions are added and is how global/static deconstructors are all called).
Just one final (obvious) note, this is written with Microsoft's runtime library in mind. It may work similar on other platforms/compilers (hopefully you'll be able to get away with just changing the segment names to whatever they use, IF they use the same scheme) but don't count on it.
atexit is processed by the C/C++ runtime (CRT). It runs after main() has already returned. Probably the best way to do this is to replace the standard CRT with your own.
On Windows tlibc is probably a great place to start: http://www.codeproject.com/KB/library/tlibc.aspx
Look at the code sample for mainCRTStartup and just run your code after the call to _doexit();
but before ExitProcess.
Alternatively, you could just get notified when ExitProcess gets called. When ExitProcess gets called the following occurs (according to http://msdn.microsoft.com/en-us/library/ms682658%28VS.85%29.aspx):
All of the threads in the process, except the calling thread, terminate their execution without receiving a DLL_THREAD_DETACH notification.
The states of all of the threads terminated in step 1 become signaled.
The entry-point functions of all loaded dynamic-link libraries (DLLs) are called with DLL_PROCESS_DETACH.
After all attached DLLs have executed any process termination code, the ExitProcess function terminates the current process, including the calling thread.
The state of the calling thread becomes signaled.
All of the object handles opened by the process are closed.
The termination status of the process changes from STILL_ACTIVE to the exit value of the process.
The state of the process object becomes signaled, satisfying any threads that had been waiting for the process to terminate.
So, one method would be to create a DLL and have that DLL attach to the process. It will get notified when the process exits, which should be after atexit has been processed.
Obviously, this is all rather hackish, proceed carefully.
This is dependent on the development platform. For example, Borland C++ has a #pragma which could be used for exactly this. (From Borland C++ 5.0, c. 1995)
#pragma startup function-name [priority]
#pragma exit function-name [priority]
These two pragmas allow the program to specify function(s) that should be called either upon program startup (before the main function is called), or program exit (just before the program terminates through _exit).
The specified function-name must be a previously declared function as:
void function-name(void);
The optional priority should be in the range 64 to 255, with highest priority at 0; default is 100. Functions with higher priorities are called first at startup and last at exit. Priorities from 0 to 63 are used by the C libraries, and should not be used by the user.
Perhaps your C compiler has a similar facility?
I've read multiple times you can't guarantee the construction order of global variables (cite). I'd think it is pretty safe to infer from this that destructor execution order is also not guaranteed.
Therefore if your memory tracking object is global, you will almost certainly be unable any guarantees that your memory tracker object will get destructed last (or constructed first). If it's not destructed last, and other allocations are outstanding, then yes it will notice the leaks you mention.
Also, what platform is this _atexit function defined for?
Having the memory tracker's cleanup executed last is the best solution. The easiest way I've found to do that is to explicitly control all the relevant global variables' initialization order. (Some libraries hide their global state in fancy classes or otherwise, thinking they're following a pattern, but all they do is prevent this kind of flexibility.)
Example main.cpp:
#include "global_init.inc"
int main() {
// do very little work; all initialization, main-specific stuff
// then call your application's mainloop
}
Where the global-initialization file includes object definitions and #includes similar non-header files. Order the objects in this file in the order you want them constructed, and they'll be destructed in the reverse order. 18.3/8 in C++03 guarantees that destruction order mirrors construction: "Non-local objects with static storage duration are destroyed in the reverse order of the completion of their constructor." (That section is talking about exit(), but a return from main is the same, see 3.6.1/5.)
As a bonus, you're guaranteed that all globals (in that file) are initialized before entering main. (Something not guaranteed in the standard, but allowed if implementations choose.)
I've had this exact problem, also writing a memory tracker.
A few things:
Along with destruction, you also need to handle construction. Be prepared for malloc/new to be called BEFORE your memory tracker is constructed (assuming it is written as a class). So you need your class to know whether it has been constructed or destructed yet!
class MemTracker
{
enum State
{
unconstructed = 0, // must be 0 !!!
constructed,
destructed
};
State state;
MemTracker()
{
if (state == unconstructed)
{
// construct...
state = constructed;
}
}
};
static MemTracker memTracker; // all statics are zero-initted by linker
On every allocation that calls into your tracker, construct it!
MemTracker::malloc(...)
{
// force call to constructor, which does nothing after first time
new (this) MemTracker();
...
}
Strange, but true. Anyhow, onto destruction:
~MemTracker()
{
OutputLeaks(file);
state = destructed;
}
So, on destruction, output your results. Yet we know that there will be more calls. What to do? Well,...
MemTracker::free(void * ptr)
{
do_tracking(ptr);
if (state == destructed)
{
// we must getting called late
// so re-output
// Note that this might happen a lot...
OutputLeaks(file); // again!
}
}
And lastly:
be careful with threading
be careful not to call malloc/free/new/delete inside your tracker, or be able to detect the recursion, etc :-)
EDIT:
and I forgot, if you put your tracker in a DLL, you will probably need to LoadLibrary() (or dlopen, etc) yourself to up your reference count, so that you don't get removed from memory prematurely. Because although your class can still be called after destruction, it can't if the code has been unloaded.

How to solve a problem in using RAII code and non-RAII code together in C++?

We have 3 different libraries, each developed by a different developer, and each was (presumably) well designed. But since some of the libraries are using RAII and some don't, and some of the libraries are loaded dynamically, and the others aren't - it doesn't work.
Each of the developers is saying that what he is doing is right, and making a methodology change just for this case (e.g. creating a RAII singleton in B) would solve the problem, but will look just as an ugly patch.
How would you recommend to solve this problem?
Please see the code to understand the problem:
My code:
static A* Singleton::GetA()
{
static A* pA = NULL;
if (pA == NULL)
{
pA = CreateA();
}
return pA;
}
Singleton::~Singleton() // <-- static object's destructor,
// executed at the unloading of My Dll.
{
if (pA != NULL)
{
DestroyA();
pA = NULL;
}
}
"A" code (in another Dll, linked statically to my Dll) :
A* CreateA()
{
// Load B Dll library dynamically
// do all other initializations and return A*
}
void DestroyA()
{
DestroyB();
}
"B" code (in another Dll, loaded dynamically from A) :
static SomeIfc* pSomeIfc;
void DestroyB()
{
if (pSomeIfc != NULL)
{
delete pSomeIfc; // <-- crashes because the Dll B was unloaded already,
// since it was loaded dynamically, so it is unloaded
// before the static Dlls are unloaded.
pSomeIfc = NULL;
}
}
My answer is the same as every time people go on about singletons: Don't effing do it!
Your singleton causes the destructors to be called too late, after some libraries have been unloaded. If you dropped the "static" and made it a regular object, instantiated in a tighter scope, it'd get destroyed before any libraries got unloaded, and everything should work again.
Just don't use singletons.
First, in the example given, I fail to see how Singleton::~Singleton() has access to pA since you declared pA as a static local variable in Singleton::getA().
Then you explained that "B" library is loaded dynamically in A* Create();. Where is it unloaded then? Why doesn't unloading of "B" library happen in void DestroyA() before invoking DestroyB()?
And what do you call "linking a DLL statically"?
Finally, I don't want to be harsh but there are certainly better designs that putting singletons everywhere: in other words, do you really need the object that manages the lifetime of "A" to be a singleton anyway? You could invoke CreateA() at the beginning of your application and rely on atexit to make the DestroyA() call.
EDIT: Since you're relying on the OS to unload "B" library, why don't you remove DestroyB() call from DestroyA() implementation. Then make the DestroyB() call when "B" library unloads using RAII (or even OS specific mechanisms like calling it from DllMain under Windows and marking it with __attribute__((destructor)) under Linux or Mac).
EDIT2: Apparently, from your comments, your program has a lot of singletons. If they are static singletons (known as Meyers singletons), and they depend on each other, then sooner or later, it's going to break. Controlling the order of destruction (hence the singleton lifetime) requires some work, see Alexandrescu's book or the link given by #Martin in the comments.
References (a bit related, worth reading)
Clean Code Talks - Global State and Singletons
Once Is Not Enough
Performant Singletons
Modern C++ Design, Implementing Singletons
At first this looks like a problem of dueling APIs, but really it's just another static destructor problem.
Generally it's best to avoid doing anything nontrivial from a global or static destructor, for the reason you've discovered but also for other reasons.
In particular: On Windows, destructors for global and static objects in DLLs are called under special circumstances, and there are restrictions on what they may do.
If your DLL is linked with the C run-time library (CRT), the entry point provided by the CRT calls the constructors and destructors for global and static C++ objects. Therefore, these restrictions for DllMain also apply to constructors and destructors and any code that is called from them.
— http://msdn.microsoft.com/en-us/library/ms682583%28VS.85%29.aspx
The restrictions are explained on that page, but not very well. I would just try to avoid the issue, perhaps by mimicking A's API (with its explicit create and destroy functions) instead of using a singleton.
You are seeing the side effects of how atexit works in the MS C runtime.
This is the order:
Call atexit handlers for handlers defined in the executable and static libraries linked with the executable
Free all handles
Call atexit handlers for handlers defined in all dlls
So if you load the dll for B manually via a handle this handle will be freed and B will be unavailable in the destructor for A which is in a dll loaded automatically.
I have had similar problems cleaning up critical sections, sockets and db connections in singletons in the past.
The solution is to not use singletons or if you have to, clean them up before main exits. eg
int main(int argc, char * argv [])
{
A* a = Singleton::GetA();
// Do stuff;
Singleton::cleanup();
return 0;
}
Or even better to use RIIA to clean up after you
int main(int argc, char * argv [])
{
Singleton::Autoclean singletoncleaner; // cleans up singleton when it goes out of scope.
A* a = Singleton::GetA();
// Do stuff;
Singleton::cleanup();
return 0;
}
As a result of the problems with Singletons I try to avoid them completely esp since they make testing hell. If i require access to the same object everywhere and don't want to pass the reference around I construct it as an instance in main, the constructor then registers itself as the instance and you access it like a singleton everywhere else. The only place that has to know it is not a singleton is main.
Class FauxSingleton
{
public:
FauxSingleton() {
// Some construction
if (theInstance == 0) {
theInstance = this;
} else {
// could throw an exception here if it makes sense.
// I generaly don't as I might use two instances in a unit test
}
}
~FauxSingleton() {
if (theInstance == this) {
theInstance = 0;
}
}
static FauxSingleton * instance() {
return theInstance;
}
static FauxSingleton * theInstance;
};
int main(int argc, char * argv [])
{
FauxSingleton fauxSingleton;
// Do stuff;
}
// Somewhere else in the application;
void foo()
{
FauxSingleton faux = FauxSingleton::instance();
// Do stuff with faux;
}
Obviously the constructor and destructor are not thread safe but normally they are called in main before any threads are spawned. This is very useful in CORBA applications where you require an orb for the lifetime of the application and you also require access to it in lots of unrelated places.
The simple answer is don't write your own code that dynamically loads/unloads DLL.
Use a framework that handles all the details.
Once a DLL is loaded it is generally a BAD idea to unload it yourself manually.
There are so many gotchas (as you have found).
The simplest solution is to never to unload the DLL (once loaded). Let that OS do that as the application exits.

Static instance of MSXML2::IXMLDOMDocument2* becoming invaild

I have a C++ dll (x.dll) which exports a class that uses a static instance of MSXML2::IXMLDOMDocument2*.
In X.dll
wrapper.h
class EXPORTEDCLASS wrapper
{
wrapper();
public:
// Some accessor methods.
private:
PIMPL* pImpl;
};
wrapper.cpp
class PIMPL
{
public:
PIMPL();
static MSXML2::IXMLDOMDocumentPtr m_pDomDocument;
static s_bInit;
static void initDomDocument();
};
PIMPL::PIMPL()
{
initDomDocument();
}
void PIMPL::initDomDocument()
{
if(!s_bInit)
{
hr = CoCreateInstance(CLSID_DOMDocument40,NULL, CLSCTX_INPROC_SERVER,
IID_IXMLDOMDocument2, (void**)&m_pDomDocument);
m_pDomDocument->load(strFileName);
s_bInit = true;
}
}
wrapper::wrapper()
{
pImpl = new PIMPL();
}
m_pDomDocument is not released anywhere. But at some places it is only assigned to some
local Smart pointers and they too are not explicitely released.
In the application the first call to the wrapper comes from DllMain of some other dll
This time the m_pDomDocument pointer is created and as such all the calls to the wrapper succeed.
When the next call comes which also happens to be from DllMain of some other dll, I find that s_bInit is true so I dont construct this object again.
But this time somehow m_pDomDocument is invalid. (Its value is same as for the first call but its vptr is invalid)
Can anybody tell me what might be going wrong here?
The issue is resolved.
There was an untimely call to CoUninitialize which used to free the COM library.
Try using this for your COM object creation:
m_pDomDocument.CreateInstance("MSXML2.DOMDocument");