Reputation: 1968
I have a generic singleton class in C++ which works in single threaded but since now I am going to multithreaded environment I want to make sure that singleton work there and one thing which is crashing is multiple threads are trying to call delete on that single pointer. Is there a way without use of locks to avoid this error.
class singleton
{
public :
static singleton* getinstance();
private :
singleton();
singleton(const singleton& that);
singleton& operator=(const singleton& that);
static singleton* ptr;
};
Upvotes: 0
Views: 215
Reputation: 154047
Where's it being deleted? A singleton is usually never deleted; if you want it destructed (which you usually don't), you use the Meyers idiom; otherwise, you allocate it once, and never delete it.
The issue of threading is more delicate. The simplest solution
is usually to ensure that the instance
function is called at
least once before threading starts, usually as the result of the
initialization of a static variable. Once the pointer is
non-null, it never changes, so there's no issue with regards to
threading. (But this has nothing to do with deleting anything.)
Upvotes: 1