lundi 26 juillet 2021

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?

Aucun commentaire:

Enregistrer un commentaire