Home > Blockchain >  Singleton creating in c
Singleton creating in c

Time:07-23

Why when we use singleton in c we create a method to construct static object of class but don't use static object? I mean why we do this:

#include <iostream>

struct Singleton {
public:
    static Singleton& instance() {
        static Singleton s;
        return s;
    }
    void getter() {
        std::cout << "asd";
    }

private:
    Singleton() = default;
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);
};

int main() {
    Singleton& s = Singleton::instance();
}

but not this:

#include <iostream>

struct Singleton {
public:
    static Singleton s;
    void getter() {
        std::cout << "asd";
    }

private:
    Singleton() = default;
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);
};

int main() {
    Singleton::s.getter();
}

I mean why does we need a method to construct static object if we can just create static object and work with it?

CodePudding user response:

The short answer is that people do what you are asking about because they want to avoid bugs resulting from global variables being initialized out of order. In particular, suppose that some other global variable made use of the singleton object in its initialization. You'd run the risk that the second object uses the first uninitialized, if the initialization happens in the wrong order. With the function-level static object, you are guaranteed that the object is initialized at the time you use it.

Note you'll need to define s in exactly one translation unit, even while it's declared in every unit (in the header file).

  • Related