Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ using static member as singleton instance leads to different object

I expected that, when we define a static member as singleton’s instance, the getInstance() should always return the same object address, so I tried:

struct singleton {
    static auto& getInstance() {
        static auto instance = std::make_unique<singleton>();
        return *instance;
    }
};
int main() {
    auto inst1 = singleton::getInstance();
    auto inst2 = singleton::getInstance();
    cout << &inst1 << endl;
    cout << &inst2 << endl;
    return 0;
} 

It prints:

0x7ffcd729efd8
0x7ffcd729efd0

inst1 and inst2 are of different address, meaning I’m creating a new object each time I call getInstance(), so it’s not a real singleton?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why different address? I think inst1 and inst2 points to same object! Would you help to explain it?

>Solution :

The class has implicitly synthesized copy constructor singleton::singleton(const singleton&) that is used when creating inst2.

//this is copy initialization
auto inst2 = singleton::getInstance(); //works because of accessible copy ctor

Same goes for inst1.

You can use auto& to create an lvalue reference(alias) or make the class non-copyable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading