Thread-safe Singleton
suggest changeSince C++11, initialization of a function-local static variable is synchronized: if several threads reach the declaration concurrently, exactly one performs the initialization and the others wait. This supports a thread-safe singleton with lazy initialization. Thread-safe initialization does not make later operations on the object thread-safe; Foo must provide its own synchronization for mutable shared state.
class Foo
{
public:
static Foo& instance()
{
static Foo inst;
return inst;
}
private:
Foo() {}
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents