Multiple Instances of Static Singleton
Posted
by Nexus
on Stack Overflow
See other posts from Stack Overflow
or by Nexus
Published on 2010-03-29T22:31:45Z
Indexed on
2010/03/29
22:33 UTC
Read the original article
Hit count: 454
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". From what I can tell when stepping through with GDB is that there are two instances of the Singleton. Why is this?
© Stack Overflow or respective owner