Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 827
bsoundra Avatar asked Nov 18 '25 03:11

bsoundra


2 Answers

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.

like image 50
Cheers and hth. - Alf Avatar answered Nov 20 '25 17:11

Cheers and hth. - Alf


Remove the copy constructor(make it private). That will prevent people from making copies.

Another alternative would be to return a pointer to the singleton for getInstance(). That would be a sure-fire way to let people know they have a reference to the singleton.

A third alternative would be to have a copyable wrapper class around the shared data. This wrapper would have a pointer or such to the singleton, and be copyable.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!