0

On executing below code, it prints "none" two times but printing different address every time, even it is declared as static variable.

class singletonDemo {
private:
    string text;
    static singletonDemo s;
    singletonDemo(string t2){ text = t2; }



public: 
    static singletonDemo getObject() {
    return s;
}

void print() {
    cout << text << endl;
}
};

singletonDemo singletonDemo::s("none");


int main() {

    singletonDemo::getObject().print();

    singletonDemo::getObject().print();

    cout << "one: "<< &(singletonDemo::getObject()) << endl;
    //cout << "print: " << single

    cout << "two: " << &(singletonDemo::getObject()) << endl;
    cout << "three: " << &(singletonDemo::getObject()) << endl;

    system("pause");

}

I'm executing this code in Visual Studio Community 2013. please help!

dplank
  • 91
  • 8
  • 3
    You return a copy of the object, but you actually want to return a reference (`singletonDemo&` or `const singletonDemo&`). – mindriot Feb 01 '16 at 10:52
  • There is not clear solution. Try to use more classic variant: [C++ Singleton design pattern](http://stackoverflow.com/a/1008289/1823963) – malchemist Feb 01 '16 at 11:05
  • Sorry, i forgot to remove "string", ya now it compiles. – dplank Feb 01 '16 at 11:09

1 Answers1

3

but printing different address every time, even it is declared as static variable.

You don't print the address of the static variable. You print the address of two separate copies of the static variable, that were returned by getObject. The progarm is ill-formed, because you're not allowed to use the address-of operator with temporary objects.

It's probably a bug that you return a copy, and you probably intended to return a reference to the static variable: static singletonDemo& getObject().

To prevent bugs like this, I would recommend not having a(n implicit) public copy or move constructor in your singleton design.

eerorika
  • 232,697
  • 12
  • 197
  • 326