Classical Meyers Singleton

This lesson gives an overview of a classical Meyers Singleton in C++.

We'll cover the following...

Here is the sequential program. The getInstance method is not thread-safe with the C++03 standard.

Press + to interact
// singletonSingleThreaded.cpp
#include <chrono>
#include <iostream>
constexpr auto tenMill = 10000000;
class MySingleton{
public:
static MySingleton& getInstance(){
static MySingleton instance;
volatile int dummy{};
return instance;
}
private:
MySingleton() = default;
~MySingleton() = default;
MySingleton(const MySingleton&) = delete;
MySingleton& operator=(const MySingleton&) = delete;
};
int main(){
constexpr auto fourtyMill = 4 * tenMill;
const auto begin= std::chrono::system_clock::now();
for ( size_t i = 0; i <= fourtyMill; ++i){
MySingleton::getInstance();
}
const auto end = std::chrono::system_clock::now() - begin;
std::cout << std::chrono::duration<double>(end).count() << std::endl;
}

As the reference implementation, I use the so-called Meyers Singleton, named after ...