Skip to content

Instantly share code, notes, and snippets.

@Jules-Baratoux
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jules-Baratoux/f81e55e0e7d22716db43 to your computer and use it in GitHub Desktop.
Save Jules-Baratoux/f81e55e0e7d22716db43 to your computer and use it in GitHub Desktop.
A wrapper turning any class into a statically allocated singleton constructed at first use.
struct object
{
int attr;
// disable the object construction outside of the singleton
private:
object() {}
friend singleton<object>;
};
instantiate_singleton_template(object);
int main(void)
{
object& first = singleton<object>();
first.attr = 42;
object& second = singleton<object>();
assert( second.attr == 42 );
assert( &first == &second );
}
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <new>
template <typename T, typename byte = uint8_t>
class singleton
{
typedef T*(function)(void);
typedef byte memory[sizeof(T) / sizeof(byte)];
static memory block;
static T* pointer;
static function* proxy;
static inline T* access(void)
{
return pointer;
}
static inline T* init(void)
{
pointer = new (&block) T;
proxy = &access;
}
public:
singleton(void)
{
proxy();
}
inline operator T& (void) const
{
return *proxy();
}
};
#define instantiate_singleton_template(T) \
template<> \
T* singleton<T>::pointer = NULL; \
\
template<> \
singleton<T>::function* \
singleton<T>::proxy = &singleton<T>::init; \
\
template<> \
singleton<T>::memory \
singleton<T>::block = {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment