I am making a C++ SDL based game engine, currently programming the AudioManager class,…
- User
I am making a C++ SDL based game engine, currently programming the AudioManager class, using SDL_mixer. I don't know if this solution is correct but it compiled, I was having troubles getting the finished playing callback set properly, is this the right way or correct?
class AudioManager { public: SoundEffect& GetSoundEffect(const std::string& filePath); void PlaySound(const std::string& filePath, int loops = 0);
codeprivate: AudioManager(); int getNextFreeChannel(); void setChannelUsage(int channel, bool used = false); static void onChannelFinish(int channel); std::vector<bool> channelsUsage; std::unordered_map<std::string, SoundEffect> soundEffects; std::unordered_map<std::string, Music> musics;};
void AudioManager::PlaySound(const std::string& filePath, int loops) { int channel = getNextFreeChannel();
codeif (channel != -1) { SoundEffect sound = GetSoundEffect(filePath); channelsUsage[channel] = true; sound.Play(loops); Mix_ChannelFinished(onChannelFinish); }}
void AudioManager::onChannelFinish(int channel) { AudioManager instance; instance.setChannelUsage(channel, false); }
void AudioManager::setChannelUsage(int channel, bool used) { channelsUsage[channel] = used; }
- Assistant
- User
Can the callback be set on the private constructor?
AudioManager::AudioManager() { Mix_AllocateChannels(16); channelsUsage.resize(16, false); Mix_ChannelFinished(onChannelFinish); }
or should I add it in the GetInstance?
AudioManager& AudioManager::getInstance() { if (!instance) { instance = new AudioManager(); Mix_AllocateChannels(16); channelsUsage.resize(16, false); Mix_ChannelFinished(onChannelFinish); } return *instance; }
- Assistant
- User
Is my GetInstance the same as yours even though the code is different?
class AudioManager { public: static AudioManager& GetInstance() noexcept; //... }
AudioManager& AudioManager::GetInstance() noexcept { static AudioManager instance;
codereturn instance;}
- Assistant
Yes, fundamentally, your version of
GetInstance()achieves the same goal as the one mentioned in my previous responses, but it does so in a different and more modern way that takes advantage of C++'s language features. Your approach uses the "Meyers' Singleton," named after Scott Meyers, a widely recommended way to implement the Singleton pattern in modern C++.