anonymous
anonymous

Reputation: 1968

avoid deletion of singleton in multithreaded environment

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

Answers (2)

user1764961
user1764961

Reputation: 693

It's better this way. Nothing to complain about. Cheers!

Upvotes: 1

James Kanze
James Kanze

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

Related Questions