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?
undefined reference to Singleton::sSingleton Singleton::s;.staticmember variable, it's different with non-static ones.