CodeBlanks Logo Icon CodeBlanks

Singleton

Learn to write a single-instance class with the Singleton pattern.

What is the Singleton pattern?

Singleton is a design pattern that ensures a class has only one instance during the whole program. This single instance is accessible from everywhere. It is common for logging, configuration or connection pools.

The cleanest way in C++ is the Meyers singleton: a method that returns a static local variable. The compiler guarantees a single instance and thread safety since C++11.

Writing the Meyers singleton

In the Meyers singleton you declare a static local variable inside the instance() method. The variable is created on the first call and the same object is returned afterwards. The constructor is made private so a second instance cannot be created with new from outside.

Example: static Singleton& instance() { static Singleton s; return s; }. The line static Singleton s; runs only once. private: Singleton() = default; blocks external construction. Copying is also disabled with = delete.

Practice Write the Singleton class

Define a Singleton class. Add a static Singleton& instance() method under public that defines static Singleton s; and returns it. Make the constructor private. In main call instance() twice and compare their addresses; if equal print "Single instance".

Starter code

main.cpp
#include <iostream>

// Define the Singleton class here

int main() {
    // Call the instance() method and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Singleton {
public:
    static Singleton& instance() {
        static Singleton s;
        return s;
    }
private:
    Singleton() = default;
};

int main() {
    auto& a = Singleton::instance();
    auto& b = Singleton::instance();
    std::cout << (&a == &b ? "Single instance" : "Many");
    return 0;
}

Expected output

Single instance

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the Singleton pattern guarantee?

  • The class runs faster
  • All methods become static
  • A single instance across the program Correct answer
  • Private members become public

Explanation: Singleton ensures only one instance of a class is created.

2 Complete the instance method

Question
static Singleton& ____() {
        static Singleton s;
        return s;
    }
Answer
static Singleton& instance() {
        static Singleton s;
        return s;
    }

Explanation: The instance() method returns the static local.

3 Match each piece to its role

Term Meaning
static Singleton& instance() Returns single instance
private Singleton() Blocks external construction
static local variable Thread safe
Meyers singleton Cleanest C++ way

All lessons in Advanced