Here is the use case. I have a singleton impl in a dll like below. In the DLL, I created a singleton instance and in my main program I also referred my singleton instance using Singleton::Instance(). Well it turned out that the instance referred in main program is different from the one created in the DLL!
// some .h file class Singleton { T& Instance() { static T instance; return instance; } }; // some cpp file Singletonm_t = Singleton ::Instance();
Why would it happen and how to resolve it?
- If the singleton is in a static library, this is OK.
- DLL is same as exe that they are a standalone linker unit, which means they are complete -- all symbols have to be resolved, while static library is not. So when static variable is in the inline function and the function is invoked in a linker unit, a storage is allocated by the linker for that static variable. In my case, I have two linker units, so I have two copies of that instance.
- Solution 1: do not inline
- Solution 2: export the static variable in DLL and import it in the main program. A common way in visual c++ is like below
// in dll // stdafx.h #define MYAPI __declspec(dllexport) // header file singleton.h class MYAPI Singleton (}; # in other linker units // stdafx.h #ifndef MYAPI #define MYAPI __declspec(dllimport) #endif // cpp of header file #include "stdafx.h" #include "singleton.h"
0 comments:
Post a Comment