I have implemented an singleton based on c++ 11. However the constructor can be called multiple times in some cases.
The class will be compiled to static lib and used by other so lib (more than one so lib). And the system is a multi-thread system (run in the Android HAL level)
/// The .h file:
class Logger
{
public:
/// Return the singleton instance of Logger
static Logger& GetInstance() {
static Logger s_loggerSingleton;
return s_loggerSingleton;
}
private:
/// Constructor
Logger();
/// Destructor
~Logger();
}
/// the .cpp file
Logger::Logger()
{
ALOGE("OfflineLogger create");
}
Logger::~Logger()
{
}
It should be created once eg:
03-21 01:52:20.785 728 4522 E : OfflineLogger create
However I can see it has been created more than once
03-21 01:52:20.785 728 4522 E : OfflineLogger create
03-21 01:52:20.863 728 2274 E : OfflineLogger create
03-21 01:52:20.977 728 2273 E : OfflineLogger create
03-21 01:52:26.370 728 4522 E : OfflineLogger create
Questions:
Anything wrong with my singleton design? Is it a thread-safe issue?
Seems like my singleton works fine in one so scope, but each so lib which includes my singleton will create its own singleton, so that my singleton is no longer “be a singleton”. Is the problem caused from each dynamic linking to new so and the "static variable" becomes "local static"? Is it possible? If so, how to fix?