Search code examples
c++oopsingletonambiguity

Singleton in CPP


Below is the code for a singleton class


class single{
private:
    int i;
    single(int x): i(x){ 

    }
public:
    static single& getInstance(){
        static single s(10);
        return s;
    }

    void incPrint(){
        ++i;
        cout i  " ";
    }
};

Now the same code gives two different results for 2 different code


single d1 = single::getInstance();
    d1.incPrint();
    d1.incPrint();

    single d2 = single::getInstance();
    d2.incPrint();
    d2.incPrint();

This code produces the output:

11 12 11 12

Whereas this code


    single & d1 = single::getInstance();
    d1.incPrint();
    d1.incPrint();

    single & d2 = single::getInstance();
    d2.incPrint();
    d2.incPrint();

produces the result

11 12 13 14

where the latter is the desired output. Is this anomaly because of design issues or user coding issues ? How to make sure only the second result is obtained ?

Thanks


Solution

  • T x = foo() makes a copy.

    Or behaves "as if" it made a copy.

    While T& x = foo(), when foo returns a T& reference, only makes a reference.


    Make the copy constructor and copy assignment operator private. That will prevent people from making copies all. Making the copy assignment operator private prevents self-copying.

    It is not an alternative to return a pointer to the singleton from getInstance. That would be a surefire way to let people be unaware of the guarantee that there's always an instance. A pointer indicates that it can be a nullpointer.

    The best alternative is, however, to not use singletons if you can avoid it. There are many problems with singletons. These problems include lifetime management, thread safety and interaction with tools that detect memory leaks.