문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top