1. 单例模式
GPT 3.5
In object-oriented programming, the Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is often used when you need to ensure that only one object of a particular class is ever created.
There are two main approaches to implementing the Singleton pattern:
Lazy Instantiation: In lazy instantiation, the instance of the class is not created until it is first accessed. This is done by using a static variable to store the instance, and checking if it is null before creating it.
Eager Instantiation: In eager instantiation, the instance of the class is created immediately when the program starts. This is done by declaring the instance as a static variable, which is initialized when the class is loaded.
In C++, the Singleton pattern can be implemented using either lazy or eager instantiation. Here is an example of a lazy instantiation implementation:
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
In this example, the instance variable is declared as a static variable, and is initialized to nullptr. The getInstance() method checks if the instance variable is nullptr, and if it is, it creates a new instance of the Singleton class and stores it in the instance variable. Otherwise, it simply returns the existing instance.
Eager instantiation can be implemented in C++ by simply declaring the instance variable as a static variable, and initializing it when the class is loaded. Here is an example:
class Singleton {
private:
static Singleton instance;
Singleton() {}
public:
static Singleton& getInstance() {
return instance;
}
};
Singleton Singleton::instance;
In this example, the instance variable is declared as a static variable, and is initialized when the Singleton class is loaded. The getInstance() method simply returns the instance variable.
StackOverflow
Why does everybody want to return a singleton as a pointer?
Return it as a reference seems much more logical!
You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don’t know (or can’t guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.
Use the static in a function method.
This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free.
class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {}
S(S const&); // Don't Implement.
void operator=(S const&); // Don't implement
};
Note you also need to make the constructor private. Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).
C++11 singleton
待补充