C++ Singleton Design Pattern

How to create a Singleton in C?

First, C is not suitable for OO programming. You'd be fighting all the way if you do. Secondly, singletons are just static variables with some encapsulation. So you can use a static global variable. However, global variables typically have far too many ills associated with them. You could otherwise use a function local static variable, like this:

 int *SingletonInt() {
static int instance = 42;
return &instance;
}

or a smarter macro:

#define SINGLETON(t, inst, init) t* Singleton_##t() { \
static t inst = init; \
return &inst; \
}

#include <stdio.h>

/* actual definition */
SINGLETON(float, finst, 4.2);

int main() {
printf("%f\n", *(Singleton_float()));
return 0;
}

And finally, remember, that singletons are mostly abused. It is difficult to get them right, especially under multi-threaded environments...

C++ Singleton design pattern

In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:

Can any one provide me a sample of Singleton in c++?

Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.

class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.

// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement

// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;

// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};

See this article about when to use a singleton: (not often)

Singleton: How should it be used

See this two article about initialization order and how to cope:

Static variables initialisation order

Finding C++ static initialization order problems

See this article describing lifetimes:

What is the lifetime of a static variable in a C++ function?

See this article that discusses some threading implications to singletons:

Singleton instance declared as static variable of GetInstance method, is it thread-safe?

See this article that explains why double checked locking will not work on C++:

What are all the common undefined behaviours that a C++ programmer should know about?

Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I

Singleton Design Pattern - Explicitly stating a Constructor outside the class

In the class the constructor was only declared, not defined. A definition includes a function body. It doesn't matter much whether you define it inline in the class, or outside the class (as you did), but one little difference is that with a definition in the class it's implicitly inline.


In other news:

  • Singletons improve on global variables by avoiding e.g. the static initialization order fiasco, but have the same problems with respect to invisible lines of communication and side effects. Best avoided.

  • If you don't need a singleton to persist after a corresponding global variable would be destroyed, then just use a simple Meyers' singleton.

Here's a Meyers' singleton:

class Foo
{
private:
Foo() {}
public:
static auto instance()
-> Foo&
{
static Foo the_instance;
return the_instance;
}
};

C++ Singletons: how good is this solution? Advantages/disadvantages, alternatives

This forces centralization of Singletons, which can mess up dependencies in more complex projects. The library that has singleton.cpp must depend on everything needed for every singleton. At the same time, anyone who uses a singleton must depend on the singleton.cpp library.

Basically your code could only work in a monolithic non-modular project. Scaling this to multiple dynamic libraries is next to impossible.

Your order of initialization must be maintained manually.

The static global variable's construction point is unsequenced with everything prior to the first expression in main.


A decent solution I've used is to create a dynamic library that holds the singleton memory.

To be a singleton, you inherit from a CRTP helper, which provides a ::Instance() inline method. People wanting the singleton use ::Instance().

::Instance() creates a static local variable lifetime token. It then attempts to get storage for the singleton from the primary DLL; if the object is already created, it simply casts the storage into the object type, and increases its reference count.

If not, it creates new storage and constructs the object in it.

At the destruction of the static local variable lifetime token, it reduces the reference count. If that reference count hits 0, it destroys it locally in the current dynamic library.

The lifetime of the singleton is now the union of the lifetime of the ::Instance() created variables. Destruction occurs in non-type-erased code, so we don't have to worry about the DLL with the code being unloaded. Storage is central. The DLL that stores the storage has to be lower level than every user of the Singleton system, but it in turn has no dependencies, so that isn't a pain.

This is far from perfect; singletons and lifetime are a constant problem, because clean program shutdown is hard and made harder by singleton's existence. But it has worked so far in a reasonably large project.

C++ singleton pattern

If you force the copy constructor and the assignment operators to be private then you won't be able to compile assignment of two Logger objects.

This will result in a linker error, which is not an explicit message.
These methods are generated by default so you have to force them to be private

In C++11 they use the deleted methods to have a clearer message

   Logger(Logger const&)=delete;             // copy constructor does not exist
Logger& operator=(Logger const&)=delete; // assignment operator does not exist

The delete is not compulsory and the singleton works well without this feature so if you don't have this supported in your compiler you can just make it private it will work.
This feature gives explicit errror messages but does not affect the behaviour of the singleton itself.

For more info about delete feature you can have a look here:

Meaning of = delete after function declaration

You can also prevent the object from being destroyed by making the destructor private.

What is the use of having destructor as private?

A base singleton object in C++

I have added a class to delete all your factories at the end. :)
You need a chain of virtual destructors for this mechanism. Beside of this, I have not found other memory leaks and the instances are unique. The security-mechanism with 'key' seems also fine. I see no way to get my hands on a key outside of the static function.

#include <iostream>
#include <set>

class Singleton;

class Set_of_Singletons
{
friend class Singleton;
private:
std::set<Singleton*> instances;

Set_of_Singletons():instances(){}
public:
~Set_of_Singletons();
};

class Singleton
{
private:
static Set_of_Singletons children;

protected:
struct key
{
private:
friend class Singleton;

key(){}
};
public:
template <class Child> static Child* doNew()
{
static key instanceKey;
Child* u = new Child(instanceKey);
children.instances.insert((Singleton*)u);
return u;
}

template <class Child> static Child* getInstance()
{
static Child* unique = doNew<Child>();
return unique;
}

Singleton(const key&)
{}

virtual ~Singleton(){}
};

Set_of_Singletons::~Set_of_Singletons()
{
for (auto inst: instances)
delete inst;

instances.clear();
}

Set_of_Singletons Singleton::children;

class B: public Singleton
{
public:
B(Singleton::key& key)
: Singleton(key)
{
std::cout << ">>>> Construction of B \n";
}

virtual ~B()
{
std::cout << "<<<< Destruction of B \n";
}

};

class C final: public Singleton
{
public:
C(Singleton::key& key)
: Singleton(key)
{
std::cout << ">>>> Construction of C \n";
}

virtual ~C()
{
std::cout << "<<<< Destruction of C \n";
}
};

int main()
{
// Object creation seems all ok
B* x = Singleton::getInstance<B>();
std::cout << "x: " << x << "\n";

B* y = Singleton::getInstance<B>();
std::cout << "y: " << y << "\n";

C* v = Singleton::getInstance<C>();
std::cout << "v: " << v << "\n";

C* w = Singleton::getInstance<C>();
std::cout << "w: " << w << "\n";
return 0;
}

// ~Have fun.~

Singleton Pattern in C [duplicate]

If you just forward declare your struct in the header file, it will be impossible for clients to create an instance of it. Then you can provide a getter function for your single instance.

Something like this:

.h:

#ifndef FOO_H
#define FOO_H

struct singleton;

struct singleton* get_instance();

#endif

.c:

struct singleton
{
char sharedData[256];
};

struct singleton* get_instance()
{
static struct singleton* instance = NULL;

if (instance == NULL)
{
//do initialization here
}

return instance;
}

simple singleton example in c++

In C++, references and pointers are different things. A reference behaves exactly like the original variable, whereas a pointer represents the memory address of that variable. You're getting the error because you're trying to assign a pointer-to-System to a variable of type reference-to-System, which isn't the same thing. If you really wanted to you could dereference the pointer by using the System& sys = *ptr; syntax, but in this case that's the wrong thing to do; the correct fix is to return a reference from your getInstance() function, rather than a pointer.

What's more, in C++ you can actually store the static instance variable within the getInstance() function. This is a so-called "magic static", otherwise known as a "Meyers Singleton", and since C++11 it guarantees you get thread-safe construction of the singleton object. So the final solution would be:

class System
{
private:
System() {}

public:
static System& getInstance(){
static System theInstance;
return theInstance;
}

void prn(){
cout<<"this works!";
}
};

int main()
{
System& sys = System::getInstance();
sys.prn();
}

Also, as an aside, you should use

#include <iostream>

not

#include "iostream"

to include standard library headers. And you don't need to say main(void) in C++; empty brackets signify that a function takes no arguments, so main() will do.

What should my Objective-C singleton look like?

Another option is to use the +(void)initialize method. From the documentation:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

So you could do something akin to this:

static MySingleton *sharedSingleton;

+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}


Related Topics



Leave a reply



Submit