Introduction to static summary static
Static is a very common modifier in C + +, which is used to control how variables are stored and visible.
A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, and the space allocated by the function on the stack is freed at the end of the function execution, creating a problem: What if you want to save the value of this variable in a function to the next call? The easiest way to think of is to define a global variable, but there are many drawbacks to defining a global variable, and the most obvious disadvantage is that it destroys the scope of access to the variable (the variable defined in this function is not only controlled by this function). The static variable can maintain the value of the variable, allowing the function to maintain the value of the last function exit at the next call.
static internal mechanism
Static is introduced to tell the compiler that the variables are stored in the program's static store rather than on the stack , and that static data members are initialized sequentially in the order in which they are defined, noting that when static members are nested, the nested members are guaranteed to be initialized.
The advantages of static:
Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency.
Static class member
The object building process of a class does not move to static variables and functions because it has static memory, it exists when the program is loaded into memory, and the object life cycle is different.
Static data member
static data member must exist when the program starts running. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function.
Static data members are physically allocated space, so they cannot be defined in the declaration of a class (only data members are declared), nor can they be defined externally within a class declaration in a header file, because that results in repeated definitions of multiple source files that use the class. The
static data member must be defined outside the body of the class definition (exactly once). Unlike normal data members, static members are not initialized by a class constructor, but rather should be initialized at the time of definition.
- In a class, static members can implement data sharing between multiple objects, and using static data members does not break the hidden principle that security is guaranteed. Therefore, a static member is a member of a class that is shared among all objects, not a member of an object.
- Static data members save memory because they are public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency.
- Initialize the format to < data type >< class name >::< static data member name >=< value >. Initialization is done outside the class body and is not preceded by static to avoid confusion with general static variables or objects.
Static member function
- Non-static members that are described in a class cannot be referenced directly in the implementation of a static member function, and can be referenced by static members that are described in the class. If you are referencing a non-static member in a static member function, you can refer to it through an object.
- A static member function, which does not belong to any specific object, has a memory area before the object declaration of the class, and the non-static data member has not allocated memory space, then uses the non-static member function in the static member function, as if not declaring a variable but using it in advance.
- The static member function does not have this pointer, cannot be declared as const, and cannot be declared as a virtual function.
Introduction to Singleton mode (Singleton)
The singleton (Singleton) mode guarantees that a class has only one instance and provides a global access point to access it.
There are many places need such a function module, such as the log output of the system, the GUI application must be a single mouse, the modem connection requires one and only need a phone line, the operating system can only have a window manager, a PC with a keyboard.
The singleton mode allows the class itself to save its only instance. This class guarantees that no other instance can be created (by intercepting a request to create a new object), and that it can provide a way to access the instance.
Applicability
- When a class can have only one instance and the customer can access it from a well-known access point.
- When this unique instance should be extensible by subclasses, and the customer should be able to use one without changing the code
An extended instance.
Structure
The singleton implementation guarantees a unique instance
The operation to create a unique instance is hidden behind a class operation (that is, a static member function), which guarantees that only one instance is created. This operation accesses the variable that holds the unique instance, and it guarantees that the variable will be initialized with the unique instance before the return value.
in C + +, you can use the static member function instance of the Singleton class to define this class operation. Singleton also defines a static member variable, _instance, which contains a pointer to a unique instance of it.
Singleton class definition:
class Singleton{ public: static Singleton* Instance(); protected: Singleton(); //构造函数为protected,当试图直接实例化Singleton类时,会得到编译时的错误信息 //保证仅有一个实例可以被创建 private: static Singleton* _instance;};Singleton* Singleton::_instance = 0;Singleton* Singleton::Instance() { if(_instance == 0){ _instance = new Singleton; } return _instance;}
Releasing the Singleton object
The Singleton class Singleton has the following characteristics:
It has a static pointer to a unique instance _pinstance, and is private;
It has a public function that can get the unique instance and create it when needed;
its constructor is private, This way, you cannot create an instance of the class from elsewhere.
We need a way to properly delete the instance
a good way is to let the class know to delete itself at the right time, or to suspend its operation on an appropriate point in the operating system, To be executed automatically at the right time.
The system automatically reconstructs all global variables at the end of the program. In fact, the system will also deconstruct the static member variables of all classes, just as these static members are also global variables. With this feature, we can define one such static member variable in a singleton class, and its only job is to delete instances of the Singleton class in the destructor.
class Csingleton {Private:csingleton () {} static Csingleton *m_pinstance; Class Cgarbo//Its only job is to delete an instance of Csingleton in a destructor {public: ~cgarbo () {if (Csingleto n::m_pinstance) Delete csingleton::m_pinstance; } }; Static Cgarbo Garbo; A static member variable is defined, and the system automatically calls its destructor public:static Csingleton * getinstance () {if (m_pinstance = = NULL) at the end of the program Determines whether m_pinstance = new Csingleton () is called for the first time; return m_pinstance; } };
When the program finishes running, the system invokes the destructor for the static member Garbo of Csingleton, which removes the singleton unique instance.
Using this method to release a singleton object has the following characteristics:
Define a proprietary nested class within a singleton class;
Defining a private static member specifically for release within a singleton class;
Using the program at the end of the analysis of the characteristics of global variables, select the final release time;
Using a singleton code does not require any action, and you do not have to care about the object's release.
Create a subclass of the Singleton class (single-piece Registry method)
Using a single-piece registry (Registry of Singleton) allows the Singleton class to register their individual instances by name in a well-known registry. The
This registry establishes a mapping between a string name and a single piece. When instance needs a single piece, it references the registry, requesting a single piece according to the name.
class singleton{public:static void Register (const char* name, Singleton *); Static singleton* Instance ();p rotected:static singleton* Lookup (const char* name);p rivate:static singleton* _insta nCE Static list<namesingletonpair>* _registry;};
register registers the singleton instance with the given name. To ensure that registration is simple, we store it in a list of Namesingletonpair objects. Each Namesingletonpair maps a name to a single piece. The lookup operation is searched based on the name of the given single piece.
singleton* singleton::instance () {if (_instance = = 0) {Const char* singletonname = getenv (" Singl ETON "); Environment supplies this at startup _instance = Lookup (singletonname); Lookup returns 0 if there ' s no such singleton} return _instance;}
The Singleton class can register itself in the constructor.
MySingleton::MySingleton() { Sinleton::Register("MySingleton",this);}
Thus, the Singleton class is no longer responsible for creating a single piece. its primary responsibility is to make the optional single-piece object accessible in the system.
Static member functions and singleton patterns for "programming supplements" C + +