Singleton: Difference between revisions

Content added Content deleted
(→‎{{header|C++}}: thread-safe singleton without mutexes in C++11)
Line 242: Line 242:


===Non-Thread-Safe===
===Non-Thread-Safe===
This version doesn't require [[Mutex#C|Mutex]], but it is not safe in a multi-threaded environment.
This version doesn't require [[Mutex#C|Mutex]], but it is not safe in a multi-threaded environment (before C++11).
<lang cpp>class Singleton
<lang cpp>class Singleton
{
{
Line 267: Line 267:
// Destructor code goes here.
// Destructor code goes here.
}
}

// And any other protected methods.
}</lang>

=== Thread safe (since C++11) ===
This will be thread safe since C++11, where static variables is always thread-safe (according to section 6.7 of The Standard).

<lang cpp>class Singleton
{
public:
static Singleton & Instance()
{
// Since it's a static variable, if the class has already been created,
// It won't be created again.
// And it **is** thread-safe in C++11.

static Singleton myInstance;

// Return a reference to our instance.
return myInstance;
}
// delete copy and move constructors and assign operators
Singleton(Singleton const&) = delete; // Copy construct
Singleton(Singleton&&) = delete; // Move construct
Singleton& operator=(Singleton const&) = delete; // Copy assign
Singleton& operator=(Singleton &&) = delete; // Move assign

// Any other public methods

protected:
Singleton()
{
// Constructor code goes here.
}

~Singleton()
{
// Destructor code goes here.
}


// And any other protected methods.
// And any other protected methods.