How do I create a destroyable threadsafe singleton C++? - c++

class Singleton
{
static std::shared_ptr<Singleton> GetInstance()
{
static std::shared_ptr<Singleton> instance = make_shared<Singleton>();
retrun instance;
}
static void DestroyInstance()
{
// What goes in here?
}
}
The reason I pass around a sharedPtr is because I don't want others to take a lock while using the Singleton in their code with the fear that it might get destroyed in a parallel thread. I can gurantee that they won't hold on to it for ever. So when DestroyInstance is called I just want the static shared_ptr<Singleton> to reduce count by one and when everyone else lets are done with their singleton it'll eventualy get destroyed. Also I'd want it such that once the Singleton is destroyed it can never be created again with GetInstance and it should simply return a nullptr.

Your other function would have to get access to a reference to the static object somehow.
What I would do is to hide the instance function privately and return a reference. The public function would return the copy of the shared pointer as usual.
struct Singleton {
static auto GetInstance() -> std::shared_ptr<Singleton> {
return GetRef();
}
static auto DropInstance() -> void {
GetRef() = nullptr;
}
private:
static auto GetRef() -> std::shared_ptr<Singleton>& {
static auto instance = std::make_shared<Singleton>();
return instance;
}
};

Related

Is Singleton with static unique_ptr a good practice

I work in a project where Singletons are usually implemented like this:
class Singleton
{
public:
static Singleton& get();
virtual ~Singleton() = default;
// Used for unit tests
static void reset();
protected:
static std::unique_ptr<Singleton>& instance();
};
unique_ptr<Singleton>& Singleton::instance()
{
static unique_ptr<Singleton> instance;
return instance;
}
Singleton& Singleton::get()
{
auto& instance = instance();
if (!instance) {
// We cannot use make_unique<T>() as constructor is private
instance = unique_ptr<Singleton>(new Singleton());
}
return *instance;
}
void Singleton::reset() { instance().reset(); }
// Private constructor
Singleton::Singleton() {}
No thread safety is required here.
Is there any advantages of using a static unique_ptr ?
What are the consequences of creating the Singleton with unique_ptr<T>(new T()) ?
Since our Singletons can carry (some) global state, a public reset() was implemented for testing purposes, is it the only way and can this be improved ?
I have found some examples of C++ singleton design patterns here.
But never implemented with unique_ptr like mine.
There are exists two ways to reset Meyer's singleton:
#include <new>
class Singleton
{
public:
static Singleton& instance() {
static Singleton instance;
return instance;
}
virtual ~Singleton() = default;
// Option 1 - easy and convinient if Singleton is copyable or movable
void reset1() {
*this = {};
}
// Option 2 - works always
void reset2() {
this->~Singleton();
new (this) Singleton;
}
private:
Singleton() {}
};
2nd option is basically doing exactly what you are doing with releasing/creating std::unique_ptr, except without deallocation/allocation of storage.
You'd get lazy instance creation if you use a pointer as opposed to a reference.
If the reset() is a logical reset, you won't need a pointer, a reference would do but, if the requirement is that of a memory reset, you'll need it.
Since the lifetime of the static singleton instance is the whole application lifetime, you don't need to care about the RAII benefit that you get with unique ptr.
But, you'd use unique_ptr to indicate exclusive ownership over the resource and some guidelines forbid using raw pointers for non-owning
The current code allows copying and moving of your instance, breaking the Singleton invariances.
There is no need to use std::unique_ptr. Use references
class Singleton
{
public:
static Singleton& instance();
virtual ~Singleton() = default;
// Used for unit tests
void reset();
private:
Singleton();
int stuff;
};
Singleton& Singleton::instance()
{
static Singleton instance;
return instance;
}
void Singleton::reset() { stuff = 0; }
// Private constructor
Singleton::Singleton() {}
Note that this design is dominated by your requirement for a reset function. This prevents you from using certain Singleton implementations, like e.g. Meyer's Singleton.
In general you would want a singleton implementation to not allow the implementation of a reset method, because now your singleton is not really a singleton anymore. But it might of course make sense to "water down" the singleton for testing purposes.
If multithreading-safety is not a concern, your singleton implementation is overly complicated and could be reduced to:
class Singleton
{
public:
static Singleton& get() {
if (!mInstance) {
mInstance = std::unique_ptr<Singleton>(new Singleton());
}
return *mInstance;
}
static void reset() { mInstance.reset(); }
private:
static inline std::unique_ptr<Singleton> mInstance{};
};

How to prevent a caller of a method from storing the result in C++

Assume I have a Singleton class. How can I prevent callers from being able to store the result of the call to getInstance() method?
I need this, since the instance of the singleton can be modified during execution and any stored instance in other classes will be invalidated. My solution would be to force all the callers to call getInstance() every time when they want to use the instance of the Singleton.
class Singleton
{
private:
static Singleton* instance;
private:
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = nullptr;
Singleton* Singleton::getInstance()
{
if (instance == nullptr)
{
instance = new Singleton();
}
return instance;
}
class A
{
private:
Singleton* m_singleton;
public:
A()
: m_singleton(Singleton::getInstance()) //This should not be possible
{
}
};
int main()
{
A a;
return 0;
}
How can I achieve this?
You cannot. If your getInstance() returns a pointer or reference, there is no way to prevent the result from being copied into some variable, the same way as you cannot prevent a result of type int or double from being copied.
You could, however, make the functions the singleton provides static:
class SomeSingleton
{
public:
static void foo();
private:
// deleting copy constructor and assignment operator...
static SomeSingleton* getInstance();
};
void SomeSingleton::foo()
{
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
So you enforce usage like this:
SomeSingleton::foo();
Some might even consider it more comfortable to use than
SomeSingleton::getInstance().foo();
By the way: This aproach makes it possible to protect you from race conditions, too, if multi-threading is or gets an issue:
class SomeSingleton
{
public:
static void foo();
private:
static std::mutex mutex; // <- add a mutex!
static SomeSingleton* getInstance();
static void exchange();
};
void SomeSingleton::foo()
{
// this must be added whenever the singleton is used...
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
void SomeSingleton::exchange()
{
// ... or the singleton instance is re-asigned
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* newInstance = new SomeSingleton();
delete instance;
instance = newInstance;
}
My solution is a wrapper with overloaded -> operator like in smart pointers which calls getInstance() inside:
class Singleton {
friend SingletonWrapper;
private:
static Singleton * getInstance() {...}
public:
void foo() {}
};
class SingletonWrapper {
public:
Singleton * operator->() {
return Singleton::getInstance();
}
};
int main() {
SingletonWrapper w;
w->foo();
}
First of all I wouldn't suggest using pointers for singletons. This ("Meyer Singleton") is a much better approach.
static SingletonDatabase &get() {
static SingletonDatabase db;
return db;
}
Also storing the singleton is kind of a bad idea, as with the storing you validate the initial idea / purpose behind the singleton: You are making copies, thus the singleton is not the "sole" instance of the class.
Anyway a great solution to your problem would be to use some kind of signal/slot system. (Qt / Boost library) Upon change you can emit the singal, which is then "caught" by all instances and the actualize the values.
Boost Signals / Slots
Qt Signals Slots
I Hope this helps :)
Use volatile to declare the singleton variable. This will force the compiler to always check for it
class Singleton
{
private:
static volatile Singleton* instance;
private:
Singleton();
public:
static volatile Singleton* getInstance();
};

When will memory be deleted in singleton?

I have seen standard(most of the people using this) singleton design pattern, but here I got confused when the memory will be deleted.
do we have to write static delete() function explicitly and delete the memory at the end ??
class ST
{
static ST* instance;
ST(){};
private :
static ST* getInstance();
};
ST* ST::instance = NULL;
ST* ST::getInstance()
{
//lock on mutex
if(NULL == instance)
{
instance = new ST();
}
return instance;
}
Yes, memory will not be freed automatically.
Probably, if you want to free singleton memory, the best way in this case is to call atexit with function, that frees singleton.
If you use C++11, the best way is to use Meyers singleton.
ST& ST::getInstance()
{
static ST instance;
return instance;
}
You create Singleton when you want there should be single instance of class, and that install will not die till end of application. So, you can delete it, because you have pointer, usually you will not.
So object will (should) persist till end of application.
To destroy the instance, you are going to want to have a static function that is used to delete the pointer and set it to NULL so that future calls to getInstance() will properly instantiate a new object.
the following would just create an infinite loop
ST~ST()
{
delete instance;
}
so we end up with the following
class ST
{
static ST* getInstance();
static void destroyInstance();
private :
static ST* instance;
ST(){};
~ST(){};
};
ST* ST::instance = NULL;
ST* ST::getInstance()
{
//lock on mutex
if(NULL == instance)
{
instance = new ST();
}
return instance;
}
void ST::destroyInstance()
{
//lock on mutex
if(NULL == instance)
{
delete instance;
instance = NULL;
}
}

Memory leak in singleton class in c++

i have a singleton class. I am creating an object of it. Using it. Once it will go out of scope destructor will be called.
Again creating anew object, since instanceFlag is false, it will again allocate new memory.
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void method()
{
cout << "Method of the singleton class" << endl;
}
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
int main()
{
Singleton *sc1,*sc2;
{
sc1 = Singleton::getInstance();
sc1->method();
delete sc1;
}
sc2 = Singleton::getInstance();
sc2->method();
return 0;
}
My doubt is what will happen to old memory? I think its a memory leak. If yes how to fix this issue in the given code?
Any comments will be helpful to understand the internals.
Pointers are variables that contain an address of something in memory. Like any other variable, a pointer can go out of scope, but that has no bearing on the information it is pointing to. This is how leaks happen.
{
char* p = new char[128];
}
When p goes out of scope, the address of the allocation goes away, but the allocation is untouched; it is still allocated and its contents unaffected any more than throwing away an envelope affects the house it was addressed to.
To solve that you would need something with ref counts, like std::shared_ptr/std::weak_ptr or a RAII container like std::unique_ptr, etc. Something that has a destructor to go out of scope with.
It's better to implement the Singleton pattern with references.
class Singleton {
Singleton() {
// constructor code...
}
static Singleton s_singleton;
public:
static Singleton& GetSingleton() {
return s_singleton;
}
};
or
class Singleton {
Singleton() = delete; // if you don't have a ctor, lets not have one at all.
public:
static Singleton& GetSingleton() {
static singleton;
return singleton;
}
};
I use valgrind which is easy to use, it is used to detect memory leak.
http://valgrind.org/docs/manual/quick-start.html
See headfirst c tutorial to detect memory leak.
sc1 and sc2 are pointers, they are not Singleton objects. There is no call to Singleton::~Singleton() when they go out of scope.
Your problem lies elsewhere. When you delete sc1, you're not setting Singleton::instanceFlag to false. That means that sc2->method() dereferences a pointer to a deleted object.
You should make the destructor private instead and introduce a new member function for deleting the object. Also, you don't really need Singleton::instanceFlag. Simply check for Singleton::single == NULL. When deleting it, set it to NULL again.
First of all, the way you have implemented singleton pattern is wrong,
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
the whole point of singleton pattern is not have multiple instance of the class, but just one. using a flag like above is not a good implementation, you are not setting flag to true and hence making new allocation of the singleton class, which indeed violated the rule of singleton pattern
You can use something like below
===========================================================
public:
static Singleton* getInstance()
{
if(! single )//check if class is already instantiated once (allocation already
//done)
{
single = new Singleton();
instanceFlag = true;
}
return single;
}
OR you can also use non pointer
public:
static Singleton& getInstance()
{
static Singleton single
return single;
}
Singletons are not supposed to be deleted.
Your question is already answered.

Using a Static Class function to create a Singleton object/instance

I am trying to create a static member function that returns a pointer to one instance of the class. Is this possible in C++?
class DynamicMemoryLog
{
// Singleton Class:
public:
static DynamicMemoryLog* CreateLog();
void AddIObject( IUnknown* obj );
void ReleaseDynamicMemory();
private:
// static DynamicMemoryLog* instance;
static bool isAlive; // used to determine is an instance of DynamicMemoryLog already exists
DynamicMemoryLog();
~DynamicMemoryLog();
std::vector <IUnknown*> iObjectList;
};
This function below should create a new instance of the class & return a pointer to that object, but the compiler will not allow me to define a static function of the class if it returns a pointer(I think thats why it wont compile?):
static DynamicMemoryLog* DynamicMemoryLog :: CreateLog()
{
// Post:
if ( !isAlive ) // ( instance == NULL; )
{
DynamicMemoryLog* instance = new DynamicMemoryLog();
return instance;
}
return NULL;
}
The particular error you're getting is that when implementing a static member function, you don't repeat the static keyword. Fixing this should resolve the error.
Independently, there's something a bit odd with your code. You claim that this object is a singleton, but each call to CreateLog will create a new instance of the class. Do you really want this behavior, or do you want there to be many copies? I'd suggest looking into this before proceeding.
Here's the simplest solution, but not thread-safe. For analysis in detail, have a look at this article.
class DynamicMemoryLog
{
public:
static DynamicMemoryLog* GetInstance();
private:
DynamicMemoryLog();
static DynamicMemoryLog* m_pInstance;
}
DynamicMemoryLog* DynamicMemoryLog::GetInstance()
{
if(!m_pInstance)
{
m_pInstance = new DynamicMemoryLog();
}
return m_pInstance;
}
I usually do something like this:
class Singleton
{
public:
static Singleton* get()
{
static Singleton instance;
return &instance;
}
};
This way you won't have any nasty memory management issues.