0

I have written following Singleton class code,

class Singleton
{
private:
    Singleton(){}

public:
    static Singleton& getInstance()
    {
        static Singleton instance; //made it static so only initialized once

        return instance;
    }
};

Now I tried to use it,

int main(int argc, char* argv[])
{

    Singleton s = Singleton::getInstance();
    Singleton s1 = Singleton::getInstance();

    cout<<&s << "   " << &s1<<endl; //why getting different address here?

    return 0;
}

Both s,s1 gives different addresses.

Sample Output:

001AFECB 001AFEBF

I am using Visual Studio 2012. I made instance object static, so it should be initialized only once, and it should not die.

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
  • 3
    You are copying your singleton. Try `Singleton &s = ...` and `Singleton &s1 = ...`. Also, disable the copy constructor. – Nemo Oct 14 '14 at 03:56
  • @Nemo Oh got it, though I am getting same instance, I am copying it to different objects? – Pranit Kothari Oct 14 '14 at 04:01
  • You have to disable to the copy constructor and assignment operator for a Singelton. See: [C++ Singleton design pattern](http://stackoverflow.com/a/1008289/14065) – Martin York Oct 14 '14 at 04:23
  • or you can start using pointers... – V-X Oct 14 '14 at 06:07

0 Answers0