Vighnesh Nayak
Vighnesh Nayak

Reputation: 181

Can this be considered as a valid implementation of singleton class in C++?

#include <iostream>
using namespace std;

class Singleton {
public:
    int val;
    static int count;
    Singleton() {
        if (count == 1) throw 0;
        Singleton::count++;
        val = 100;
    }
};

int Singleton::count = 0;

int main () {
    try {
        Singleton a, b;
    } catch (...) {
        cout << "error\n";
    }
    return 0;
}

So we count the number of objects created, and throw from the constructor when count is about to exceed 1. Will throwing from constructor abort the creation of object?

Upvotes: 2

Views: 112

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

C++11 and above:

You make your constructor private and define a static instance in a static function. It synchronizes construction so the object is constructed once no matter how many threads try to access it:

class Singleton {
private:
    Singleton() { /* ... */ }

public:
    static auto& instance() {
        static Singleton singleton;
        return singleton;
    }
};

Pre C++11:

Before C++11 (C++03, C++98) there is no standard way to synchronize object construction. You need to use OS-specific tricks to make it work.

If you have a single-threaded program, and thus don't care about the synchronization, you can use the same version as above.

Upvotes: 3

Related Questions