When will memory be deleted in singleton? - c++

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;
}
}

Related

How do I create a destroyable threadsafe singleton 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;
}
};

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();
};

C++ singleton in constructor

Is this possible?
class A {
static A *instance = NULL;
public:
A () {
if (instance) {
this = instance;
} else {
instance = this;
}
}
}
Does it have leak memory?
Do I need to oveload new operator?
No. Overlooking your compiler errors, your class won't work.
#Galik has provided invaluable sources for how you'd actually want to construct a singleton. But let's look at yours.
class A {
static A *instance = NULL; // NULL isn't even a thing, but assuming you mean nullptr you can't assign a static like this
public:
A () {
if (instance) {
this = instance; // this can't be assigned
} else {
instance = this; // this is correct
}
}
};
Which would give you the following:
class A {
static A *instance;
public:
A () {
// if there's no instance, this is the one we'll use
if (!instance) {
instance = this;
}
}
};
A* A::instance = nullptr;
Which doesn't stop you from constructing more than one anyway.
Not possible. If the constructor is exposed and called, a new object of A is inevitably created. The most elegant and widely used implementations of C++ singleton classes use static methods to return the single static instance, while hiding (e.g. make private accessible) the constructor.
Here's an example:
class A {
private:
static A *instance_; // use nullptr since C++11
A() {}
public:
static A& instance() {
if (!instance_)
instance_ = new A();
return *instance_;
}
};
A* A::instance_ = nullptr;
You cannot assign a value for this

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.