From 6d499d4e3a7c69a1ba5658937d797af1f1b3e97c Mon Sep 17 00:00:00 2001 From: Bim Overbohm Date: Mon, 27 May 2013 12:38:39 +0200 Subject: [PATCH] Improve singleton implementation Still not thread-safe, but a bit better now. Should be made thread-safe and maybe get converted to a template, if possible. --- src/VolumeControl.cpp | 24 ++++++++++++++++++++---- src/VolumeControl.h | 6 ++++-- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/VolumeControl.cpp b/src/VolumeControl.cpp index 45a442e02..95ac7535a 100644 --- a/src/VolumeControl.cpp +++ b/src/VolumeControl.cpp @@ -12,7 +12,7 @@ const char * VolumeControl::mixerCard = "default"; #endif -std::shared_ptr VolumeControl::sInstance; +std::weak_ptr VolumeControl::sInstance; VolumeControl::VolumeControl() @@ -31,6 +31,20 @@ VolumeControl::VolumeControl() originalVolume = getVolume(); } +VolumeControl::VolumeControl(const VolumeControl & right) +{ + sInstance = right.sInstance; +} + +VolumeControl & VolumeControl::operator=(const VolumeControl & right) +{ + if (this != &right) { + sInstance = right.sInstance; + } + + return *this; +} + VolumeControl::~VolumeControl() { //set original volume levels for system @@ -42,10 +56,12 @@ VolumeControl::~VolumeControl() std::shared_ptr & VolumeControl::getInstance() { //check if an VolumeControl instance is already created, if not create one - if (sInstance == nullptr) { - sInstance = std::shared_ptr(new VolumeControl); + static std::shared_ptr sharedInstance = sInstance.lock(); + if (sharedInstance == nullptr) { + sharedInstance.reset(new VolumeControl); + sInstance = sharedInstance; } - return sInstance; + return sharedInstance; } void VolumeControl::init() diff --git a/src/VolumeControl.h b/src/VolumeControl.h index abfa4a556..8f35ea2c2 100644 --- a/src/VolumeControl.h +++ b/src/VolumeControl.h @@ -39,9 +39,11 @@ class VolumeControl int originalVolume; int internalVolume; - static std::shared_ptr sInstance; + static std::weak_ptr sInstance; VolumeControl(); + VolumeControl(const VolumeControl & right); + VolumeControl & operator=(const VolumeControl & right); public: static std::shared_ptr & getInstance(); @@ -52,5 +54,5 @@ public: int getVolume() const; void setVolume(int volume); - virtual ~VolumeControl(); + ~VolumeControl(); };