C++ singleton pattern using boost::call_once - c++

Singletons in C++ (at least prior C++11 AFAIK) can be a nightmare. With the whole static initialisation order fiasco. But boost::call_once seems to offer a robust way to implement singletons. I've tried to come up with an easy to use idiom I'd like to share for some critical feedback, hope I haven't been completely foolish :)
// Usage:
// You can make anything with a public or protected ctor a singleton.
//
// class A
// {
// public:
// ~A();
// public:
// // Optional, shorter to type
// static A& Instance() { return Singleton<A>::Instance(); }
// void foo();
//
// protected:
// explicit A(); // Can't be private, but can be public, protected is recommended.
// };
//
// Singleton<A>::Instance().foo();
// A::Instance().foo();
//
template< class T >
class Singleton : public T // inerits from T so we can access the protected constructor.
{
public:
virtual ~Singleton() {}
public:
static T& Instance();
private:
static boost::once_flag s_onceFlag;
// We use a raw pointer to avoid dynamic initialisation. If something that
// has a constructor (eg, shared_ptr ) then the dynamically initialised ctor
// may get called after the call once function is called (if the call once function
// is statically invoked before main). Then the instance pointer will be overwritten.
// Using a zero initialised pointer avoids this problem.
static T* s_instance;
private:
static void Init();
private:
explicit Singleton() {} // Used only to allow access to the protected ctor in base.
};
template< class T >
boost::once_flag Singleton<T>::s_onceFlag = BOOST_ONCE_INIT; // zero initialised variable, no order o initialisation shananigans
template< class T >
T* Singleton<T>::s_instance = 0;
template< class T >
void Singleton<T>::Init()
{
static Singleton<T> instance; // static local variable is thread safe since this function is called once only.
s_instance = &instance;
}
template< class T >
T& Singleton<T>::Instance()
{
boost::call_once( s_onceFlag, Init );
return *s_instance;
}

To be fair, I expect that call_once is a threading specific version of something that can already been had in c++11 using just a function local static initializer:
template< class T >
T& Singleton<T>::Instance()
{
static bool const init = [] () -> bool { Init(); return true; }();
return *s_instance;
}
The initializer is guaranteed not to race (in the language specification).
Worst case behaviour is when the initializer throws: the exception will propagate out of the Instance() method but next time will try to initialize again, because the specification deems the variable to have "not been initialized" when the initializer expression throws.
If in fact you "need" a thread-aware singleton (e.g. instance per thread), then you may want the thread_local keyword, with largely the same semantics.

Related

Who is responsible for destructing the block scoped static Singleton instance?

I couldn't understand how the program below compiles successfully.
class SomeClass {
public: /** Singleton **/
static SomeClass &instance() {
static SomeClass singleInstance;
return singleInstance;
};
private:
SomeClass() = default;
SomeClass(const SomeClass&) = delete;
SomeClass &operator=(const SomeClass&) = delete;
~SomeClass() {}
};
int main()
{
SomeClass::instance();
// SomeClass::instance().~SomeClass(); // Compiles if destructor was public
return 0;
}
Who is responsible for calling the destructor of the Singleton
instance?
How does the underlying mechanism access a private method?
Shortly, during the construction, the compiler saves the destructor to a list of functions that will be called at the very end of the program. In the end, the list of functions, including the destructors, are called one by one and the safe destruction occurs.
Underlying Mechanism
The core of the mechanism is the exit() and atexit(..) functions provided by the C standard library. During the compilation of the program, the compiler injects some other codes around your block-scoped static variable. A pseudo representation is as below.
static SomeClass& instance() {
static SomeClass singleInstance;
/*** COMPILER GENERATED ***/
// Guard variable generated by the compiler
static bool b_isConstructed = false;
if(!b_isConstructed)
ConstructInstance(); // Constructs the Singleton instance
b_isConstructed = true;
// Push destructor to the list of exit functions
atexit(~SomeClass());
}
/*** COMPILER GENERATED ***/
return singleInstance;
};
The point here is to call the atexit(~SomeClass()) and register the destructor to the automatic call list of the exit() function which is implicitly called when you return from the main(..). As the function pointers are used instead of directly referring to the private destructor method, the access specifier protection mechanism is skipped.

C++ Singleton Instance disable re-call

When using the Meyers singleton:
class Singleton
{
public:
static Singleton& instance()
{
static Singleton instance;
return instance;
}
void Hello()
{
std::cout <<"Hello!\n";
}
protected:
Singleton() = default;
~Singleton() {};
private:
Singleton(Singleton const&);
Singleton& operator=( Singleton const& );
};
You are able to call the instance as follow:
Singleton::instance().Hello();
or
Singleton& s = Singleton::instance();
s.Hello();
But I'm wondering if there is a way to block this:
Singleton::instance().instance();
How to avoid to call instance() as a method (with the .) and only support the static call with the :: ?
Is there a way to use static_assert, template enable_if or anything else?
First, I don't think this is a practical concern. Nobody is going to write Singleton::instance().instance().instance().Hello(). Or rather, if people are writing that on purpose, I think you have bigger problems. This is fine, as-is.
If you really want to prevent that, then you just have to move instance() outside of the class so it ceases to be a member function. There's nothing for you to assert or constrain, since you cannot tell if your static member function was called on an object or not (and you cannot overload a static member function with a non-static one taking the same argument list). Either you can write both Singleton::instance() and Singleton::instance().instance(), or neither.
Simplest is just:
class Singleton {
// ...
friend Singleton& make_singleton();
};
Singleton& make_singleton() {
static Singleton instance;
return instance;
}
Now it's just make_singleton().Hello(), and there's no other way to write that at all. This can be arbitrarily generalized by wrapping it in a singleton class template factory:
template <typename T>
struct SingletonFactory
static T& instance() {
static T instance;
return instance;
}
};
SingletonFactory<Singleton>::instance().Hello(); // ok
SingletonFactory<Singleton>::instance().instance().Hello(); // error

is there anything wrong with this Singleton class

Under these condition i wrote the next Singleton class :
1 - i want one and only one instance of the class to be present and to be accessible from the whole game engine .
2 - the Singleton is intensively used ( thousands times per frame) so i dont want to write an extra GetInstance() function , im trying to avoid any extra function call for performance
3 - one possibility is to let the GetInstance() be inlined like this :
inline Singleton* Singleton::GetInstance()
{
static Singleton * singleton = new Singleton();
return singleton;
}
but that will cause a reference problem , on each call there will be a new reference to the singleton , to fix that wrote in c++ :
class Singleton{
private:
static Singleton* singleton;
Singleton(){}
public:
static inline Singleton* GetInstance() // now can be inlined !
{
return singleton;
}
static void Init()
{
// ofc i have to check first if this function
// is active only once
if(singleton != nullptr)
{
delete singleton;
}
singleton = new Singleton();
}
~Singleton(){} // not virtual because this class can't be inherited
};
Singleton* Singleton::singleton = nullptr;
What are the possible problems i can face with this implementation ?
Your first implementation problem is a leak of the only new you call.
And the signature that force user to check pointer validity.
Your second implementation has even more problem as you require to use a 2-step initialization, and don't forbid copy/move/assignment.
Simply use Meyers' singleton:
class Singleton{
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton operator&(const Singleton&) = delete;
public:
static Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
};
In addition to #Jarod42's answer, I would like to point out that you could also implement a generic singleton by making template and use it in a CRTP class:
template<typename T>
class Singleton {
protected:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton operator&(const Singleton&) = delete;
public:
static T& instance() {
static T instance;
return instance;
}
};
Then extend it:
struct MySingleton : Singleton<MySingleton> { /* ... */ };
Instead of a singleton, consider a namespace! Here's how I would do it:
// thing.h
namespace thing {
// public interface
int doSomething();
}
// thing.cpp
namespace thing {
namespace {
// private data and functions can go right here :-)
int private_data_ = 1234;
int doSomethingInternal() {
return private_data_ * 2;
}
}
// public interface
int doSomething() {
return doSomethingInternal();
}
}
Usage is simple like this:
int x = thing::doSomething();
No need for getInstance(), no memory leaks, and you can't accidentally make multiple instances.
but that will cause a reference problem , on each call there will be a new reference to the singleton
Incorrect; instead there will be a new class instance which is not the same as a reference. You will most likely end up leaking memory.
static Singleton* singleton;
Use a unique_ptr instead of a raw pointer. Compiler optimizations will devolve it into a raw pointer anyway, but now you're clearly telling the compiler what its lifespan should be.
class Singleton{
private :
static Singleton* singleton;
The default scope of a class is private; you don't need to explicity say private scope.
Singleton(){}
There is no need to provide an empty constructor when you have no other constructors in the class.
im trying to avoid any extra function call for performance
Compiled C++ will often inline such code anyway.
inline Singleton* GetInstance() // now can be inlined !
Make it static...?
~Singleton(){} // not virtual because this class can't be inherited
If your intent is to make it not inheritable, then add a final keyword to the class declaration. You can then remove the destructor.

Is this standard way to derive from singleton class?

My Base class is Singleton having protected c'tor. Now, I can derive another class from it but I cannot create instance of that Base class inside functions of derived class. This is expected behavior as per my design. But I like to know is it correct by C++ standards or just my compiler specific behavior? (So that I shouldn't face issues if I want to port this code in future)
class Singleton
{
protected:
Singleton() {}
public:
Singleton * GetInstance()
{
static Singleton* InstanceCreated = NULL ;
if (!InstanceCreated)
InstanceCreated = new Singleton ;
return InstanceCreated ;
}
};
class Deringlton : public Singleton
{
public:
Deringlton()
{
Singleton * pSing ;
// pSing = new Singlton ; // Cannot create object of singlton
// (Despite class is derived from singlton)
}
};
I think a better way to provide a generic singleton implementation is to use the CRTP and directly inheriting from that template. That means every class automagically implements the singleton pattern only inheriting from the CRTP base:
template<typename DERIVED>
class generic_singleton
{
private:
static DERIVED* _instance;
static void _singleton_deleter() { delete _instance; } //Function that manages the destruction of the instance at the end of the execution.
protected:
generic_singleton() {}
virtual ~generic_singleton() {} //IMPORTANT: virtual destructor
public:
DERIVED& instance() //Never return pointers!!! Be aware of "delete Foo.instance()"
{
if(!_instance)
{
_instance = new DERIVED;
std::atexit( _singleton_deleter ); //Destruction of instance registered at runtime exit (No leak).
}
return static_cast<DERIVED&>( _instance );
}
};
template<typename DERIVED>
DERIVED* generic_singleton<DERIVED>::_instance = nullptr;
The memory release is provided by registering a function that does the delete at the end of the application, with std::ateexit().
What's the point of having a pointer an not just a static variable?
class Singleton
{
public:
static Singleton& instance()
{ static Singleton z; return z; }
private:
Singleton() {}
~SIngleton() {}
};
In don't see any value in deriving it.
If you want to make this pattern coded as a template you can do
template<class S>
S& instance_of() { static S z; return z; }
and make instance_of<yourclass>() a friend of yourclass, having private ctor / dtor.
The use of a static variable makes the object granted to be properly constructed and destructed. (Unlike a remaining leaked pointer, with no destructor call...)
If you have to make a singleton (which you should avoid) the instance and(!) the declaration are a singleton. You could use a template have a 'generic' one, but inheritance is no good.
This is expected behaviour. The rule is you can only access protected members in Deringlton if the pointer is of type Deringlton. You cannot access protected members through a pointer of type Singleton. For example:
Deringlton* d = this;
d->someProtectedMethod(); // OK!
Singleton* s = this;
s->someProtectedMethod(); // Will fail
Since accessing new Singleton is not through a Deringlton pointer, it is not allowed. You can only access it through Deringlton by doing new Deringlton.
This behavior is specified in the standard.
Section 11.4 [class.protected] of C++11 states (emphasis mine):
As described earlier, access to a protected member is granted because
the reference occurs in a friend or member of some class C. If the
access is to form a pointer to member (5.3.1), the
nested-name-specifier shall denote C or a class derived from C. All
other accesses involve a (possibly implicit) object expression
(5.2.5). In this case, the class of the object expression shall be C
or a class derived from C.
What this means is that access to the base constructor is granted only if you are creating an object of the derived class. So for example, this would compile:
Deringlton()
{
Deringlton* p = new Deringlton();
}

Possible to make a singleton struct in C++? How?

I like to experiment around as I learn more about coding. I have a program that would only require a single instance of a struct for the life of it's runtime and was wondering if it's possible to create a singleton struct. I see lot's of information on making a singleton class on the internet but nothing on making a singleton struct. Can this be done? If so, how?
Thanks in advance. Oh, and I work in C++ btw.
A class and a struct are pretty much the same thing, except for some minor details (such as default access level of their members). Thus, for example:
struct singleton
{
static singleton& get_instance()
{
static singleton instance;
return instance;
}
// The copy constructor is deleted, to prevent client code from creating new
// instances of this class by copying the instance returned by get_instance()
singleton(singleton const&) = delete;
// The move constructor is deleted, to prevent client code from moving from
// the object returned by get_instance(), which could result in other clients
// retrieving a reference to an object with unspecified state.
singleton(singleton&&) = delete;
private:
// Default-constructor is private, to prevent client code from creating new
// instances of this class. The only instance shall be retrieved through the
// get_instance() function.
singleton() { }
};
int main()
{
singleton& s = singleton::get_instance();
}
Struct and class are in C++ almost the same (the only difference is default visibility of members).
Note, that if you want to make a singleton, you have to prevent struct/class users from instantiating, so hiding ctor and copy-ctor is inevitable.
struct Singleton
{
private:
static Singleton * instance;
Singleton()
{
}
Singleton(const Singleton & source)
{
// Disabling copy-ctor
}
Singleton(Singleton && source)
{
// Disabling move-ctor
}
public:
Singleton * GetInstance()
{
if (instance == nullptr)
instance = new Singleton();
return instance;
}
}
Conceptually, a struct and a class are the same in C++, so a making singleton struct is the same as making a singleton class.
The only difference between class and struct are the default access specifiers and base class inheritance: private for class and public for struct. For example,
class Foo : public Bar
{
public:
int a;
};
is the same as
struct Foo : Bar
{
int a;
};
So, there is no fundamental difference when it comes to singletons. Just make sure to read about why singletons are considered bad.
Here's a simple implementation:
struct singleton
{
static singleton& instance()
{
static singleton instance_;
return instance_;
}
singleton(const singleton&)=delete; // no copy
singleton& operator=(const singleton&)=delete; // no assignment
private:
singleton() { .... } // constructor(s)
};
First off, struct and class only refer to the default access of members. You can do everything with a struct that you can do with a class. Now if you were referring to POD structs, things get more complicated. You can't defined a custom constructor, so there's no way to enforce only a single object creation. However, there's nothing stopping you from simply only instantiating it once.
class and struct is almost a synonyms in C++. For singleton use case they are complete synonyms.