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?