Categories
C++

C++ – Singleton Implementation

C++ Singleton Implementation

#pragma once //////////////////////////////////////////////////////////// #include <cassert> #ifdef __APPLE__ #define nullptr NULL #endif //////////////////////////////////////////////////////////// template <typename S> class Singleton { public: Singleton() { assert(!s_instance); s_instance = static_cast<S*>(this); } virtual ~Singleton() { assert(s_instance); s_instance = 0; } static S* Instance() { return s_instance; } private: static S* s_instance; }; template <typename S> S* Singleton<S>::s_instance = nullptr; ////////////////////////////////////////////////////////////

How to use

Read more…

Categories
C++

C++ – Why make the constructor Explicit

The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

Here’s an example class with a constructor that can be used for implicit conversions:

Read more…

Categories
C++

C++ in-class initialization

The two code snippets you posted are not quite equal.

class Something { int m_a = 0; };

Here you specify the value with which to initialize, i.e. 0, at compile time.

class Something { int m_a; Something(int p_a); }; Something::Something(int p_a):m_a(p_a){ … };

And here you do it at run time (or possibly at run time), with the value p_a not known until the
Read more…