Question

I've recently been working with code that looks like this:

using namespace std;

class Singleton {
    public:
        static Singleton& getInstance();
        int val;
};

Singleton &Singleton::getInstance() {
    static Singleton s;
    return s;
}

class Test {
    public:
        Test(Singleton &singleton1);
};

Test::Test(Singleton &singleton1) {
    Singleton singleton2 = Singleton::getInstance();
    singleton2.val = 1;
    if(singleton1.val == singleton2.val) {
        cout << "Match\n";
    } else {
        cout << "No Match " << singleton1.val << " - " << singleton2.val << "\n";
    }   
}

int main() {
    Singleton singleton = Singleton::getInstance();
    singleton.val = 2;
    Test t(singleton);
}

Every time I run it I get "No Match". Yet I am expecting a match since there should only be one instance of the class. From what I can tell when stepping through with GDB is that there are two instances of the Singleton. Why is this?

Was it helpful?

Solution

The first line of Test::Test creates another instance of Singleton (on the stack, your local isn't a reference). You could prevent this by defining the default constructor on Singleton and making it private. As it stands, anybody can create an instance of Singleton.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top