I have a number of static members of classes interacting. One of them never gets initialized.
I am trying to implement an common interface for audio devices, whatever the API. I register all APIs with a manager class. Since API objects and the manager objects are singletons I use static objects.
AudioDevice.h
Code:
class AudioDeviceAPI
{
public:
virtual ~AudioDeviceAPI();
virtual uint32 GetDeviceCount() const = 0;
virtual AudioDevice* GetDevice(uint32 index) const = 0;
void RegisterWithManager();
protected:
AudioDeviceAPI();
String mName;
};
typedef std::map<String, AudioDeviceAPI*> APIMap;
class AudioDeviceManager
{
public:
static AudioDeviceManager& Get();
~AudioDeviceManager();
uint32 GetDeviceCount() const;
AudioDevice* GetDevice(uint32 DeviceIndex);
protected:
AudioDeviceManager();
friend void AudioDeviceAPI::RegisterWithManager();
void RegisterAPI(const String& rAPIName, AudioDeviceAPI* pAPI);
APIMap mAPIs;
int32 mDeviceCount;
static AudioDeviceManager* gpManager;
};
AudioDevice.cpp
Code:
void AudioDeviceAPI::RegisterWithManager()
{
AudioDeviceManager::Get().RegisterAPI(mName, this);
}
AudioDeviceManager& AudioDeviceManager::Get()
{
if (!gpManager)
{
gpManager = new AudioDeviceManager();
}
return *gpManager;
}
void AudioDeviceManager::RegisterAPI(const String& rAPIName, AudioDeviceAPI* pAPI)
{
APIMap::const_iterator end = mAPIs.end();
APIMap::const_iterator it = mAPIs.find(rAPIName);
if (it != end)
{
delete it->second;
}
mAPIs[rAPIName] = pAPI;
}
AudioDeviceManager* AudioDeviceManager::gpManager = NULL;
This is the (simplified) interface I use. The actual API implementations are subclasses of AudioDeviceAPI.
For example:
AudioDevice_DirectSound.cpp
Code:
/* definition of AudioDeviceAPI_DirectSound goes here */
AudioDeviceAPI_DirectSound::AudioDeviceAPI_DirectSound()
{
mName = "DirectSound";
RegisterWithManager();
}
static AudioDeviceAPI_DirectSound DirectSoundAPI;
AudioDevice_ASIO.cpp
Code:
/* definition of AudioDeviceAPI_ASIO goes here */
AudioDeviceAPI_ASIO::AudioDeviceAPI_ASIO()
{
mName = "ASIO";
RegisterWithManager();
}
static AudioDeviceAPI_ASIO AsioAPI;
The Problem: The static instance of AudioDeviceAPI_ASIO is initialized. The DirectSound one isn't... I first had to make the singleton pattern around the manager (with the NULL init, and static getter) to ensure that it would always be constructed before the AudioDeviceAPI instances. But the DirectSound API is just never instantiated. No cout, no breakpoint...
I have found a workaround using a bogus function forcing instantiation, but I'd like to know why it doesn't work.
Working with Visual Studio 2005, if that'll help.