In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "C++ singleton model case analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Classes that cannot be copied
Copies are only released in two scenarios: copy constructor and assignment operator overloading, so if you want a class to disable copying, simply make it impossible for the class to call the copy constructor and assignment operator overloading.
Clippers 98
Overloading the copy constructor and assignment operator simply declares it undefined and sets its access to private.
Class CopyBan {/ /... private: CopyBan (const CopyBan&); CopyBan& operator= (const CopyBan&); / /...}
Reason:
Set to private: if you only declare that it is not set to private, if you define it outside the class, you can not prohibit copying.
Just declare no definition: no definition because the function will not be called at all, there is no point in defining it, it is easy not to write, and if it is defined, it will not prevent internal copies of member functions.
Central11
Clocking 11 extends the use of delete. In addition to releasing the resources requested by new, if delete is followed by = delete after the default member function, it means that the compiler will delete the default member function.
Class CopyBan {/ /... CopyBan (const CopyBan&) = delete; CopyBan& operator = (const CopyBan&) = delete; / /...}; classes that can only create objects on the heap
Implementation method:
Declare the constructor of the class private and the copy constructor private. Prevents others from calling copy to generate objects on the stack.
Provides a static member function in which to complete the creation of the heap object
Class HeapOnly {public: / / provides a static public function to create objects. All the objects created are on the heap static HeapOnly* CreateObject () {return new HeapOnly;} private: HeapOnly () {} / / anti-copy 98 only declares that HeapOnly (const HeapOnly&) is not implemented; / / HeapOnly (const HeapOnly&) = delete;} Classes of objects can only be created on the stack
Method 1: privatize the constructor as above, and then design a static method to create an object to return.
Class StackOnly {public: StackOnly () {} public: / / void* operator new (size_t size) = delete; void operator delete (void* p) = delete;private: / / void* operator new (size_t size); void operator delete (void* p);}
Shielding new
Because new calls the void* operator new (size_t size) function at the bottom, you just need to mask the function. Note: also prevent positioning new
Class StackOnly {public: StackOnly () {} private: void* operator new (size_t size); void operator delete (void* p);} Class C++98//C++98 that cannot be inherited is not direct enough / / it can be inherited here, but Derive cannot create an object because the constructor of Derive must call the parent class NonOnherit construction, but the constructor of NonInherit is private and private is not visible in the subclass, so inheritance will not report an error. Inherited subclasses create objects that report an error class NonInherit {public: static NonInherit GetInstance () {return NonInherit () } private: NonInherit () {}}; Clear11
The final keyword, the final modifier class, indicates that the class cannot be inherited.
Class A final {/ /...}; A class (singleton pattern) design pattern that can only create one object.
Design patterns (Design Pattern) are a set of repeatedly used, well-known, classified, code design experiences. Why do things like design patterns come into being? Just like the development of human history will give rise to the art of war. In the beginning, when there was a war between tribes, people fought against each other. Later, during the Spring and Autumn and warring States period, there were frequent wars between the Seven Kingdoms, and it was found that there were tricks in fighting. Later, Sun Tzu summed up Sun Tzu's Art of War. Sun Tzu's Art of War is similar.
The purpose of using design patterns: for the reusability of the code, to make the code easier for others to understand, and to ensure the reliability of the code. Design patterns make code writing truly engineering; design patterns are the cornerstone of software engineering, just like the structure of a building.
Singleton mode
Defining a global object can be used by everyone and can guarantee singletons, but this approach has great defects. If you want everyone to use it, the object can only be defined in one .h. If this .h is contained in multiple .cpp, then the link will report an error. Global static, visible only in the current file, is no longer the same object, and each xxx.cpp is an object. Extern can ensure that links do not report errors, but there is no guarantee that there is only one v globally, and there may be a variable v redefined somewhere, so we can declare it in .h, define it in .cpp, and separate declaration and definition. Otherwise, multiple cpp inclusions will have multiple copies as defined in .h.
Some classes, which should have only one object (instance), are called singletons.
In many server development scenarios, it is often necessary for the server to load a lot of data (hundreds of gigabytes) into memory. At this point, a singleton class is often used to manage the data.
There are two implementation modes of singleton mode: hungry man and lazy man.
Example of washing dishes: wash the dishes immediately after eating. This is the hungry man's way. Because you can eat with a bowl right away when you eat the next meal. After eating, put the bowl down first, and then wash the dishes after the next meal, which is the lazy way. The core idea of the lazy approach is "delayed loading". Thus, the startup speed of the server can be optimized.
Hungry man model
Create an object from the beginning before the main function
.h:
/ / hungry mode: before the main function, the object / / global as long as the unique Singleton instance object is created, then the member in it is the singleton class Singleton {public: / / 3. Provide a static member function static Singleton& GetInstance () to get the singleton object; / / if the vector object is private and you want to access it, you can only encapsulate one layer of / / void PushBack (int x) / / {/ / _ v.push_back (x); / /} vector _ v.push_back: / / vector _ v; / / 1. The constructor is privatized, and the object Singleton () {} / / anti-copy Singleton (const Singleton&) = delete; Singleton& operator= (const Singleton&) = delete; / / 2 cannot be created at will. Declare a static Singleton object in the class. Define this object in cpp / / ensure that there is only one unique object globally / / the static here is analogous to a global variable, but limited by the class domain and does not change the link property static Singleton _ sinst;}
.cpp:
# include "Singleton.h" / / define Singleton Singleton::_sinst;Singleton& Singleton::GetInstance () {return _ sinst;}
Pros: simplicity
Cons: initialization is created before the main function. If a lot of work is done in the constructor of the singleton object, it may cause the process to start slowly.
And if there are multiple singleton class object instances, the startup order is uncertain.
If this singleton object is frequently used in a multi-threaded environment with high concurrency and high performance requirements, then obviously using hungry mode to avoid resource competition and improve response speed is better.
Lazy man mode
The hungry Han style creates an instance when the application is started. The hungry Han style is thread-safe and is an absolute singleton. The lazy type instantiates the object when the externally provided get method is called. In the case of multithreading, lazy mode is not thread-safe.
The first time you use an instance object, create an object. The process starts with no load. The startup sequence of multiple singleton instances is controlled freely.
/ / define Singleton* Singleton::_spinst = nullptr;mutex Singleton::_mtx;Singleton& Singleton::GetInstance () {/ / A double check lock to improve efficiency if (_ spinst = = nullptr) {_ mtx.lock () If (_ spinst = = nullptr) {/ / first call _ spinst = new Singleton;} _ mtx.unlock ();} return * _ spinst } void Singleton::DelInstance () {if (_ spinst! = nullptr) {_ mtx.lock (); if (_ spinst! = nullptr) {delete _ spinst; _ spinst = nullptr;} _ mtx.unlock ();}}
# pragma once#include # include # include using namespace std;// lazy mode: initialization singletons are created only when GetInstance is called for the first time / / compared with hungry people, there is no problem that may lead to slow startup, and the problem of sequence dependence can also be controlled. Class Singleton {public: / / 3. Provide a static member function static Singleton& GetInstance () to get the singleton object; / / if the vector object is private and you want to access it, you can only encapsulate one layer of / / void PushBack (int x) / / {/ / _ v.push_back (x); / /} vector _ v / / or implement an embedded garbage collection class class CGarbo {public: ~ CGarbo () {if (Singleton::_spinst) delete Singleton::_spinst;}} / / define a static member variable, when the program ends, the system will automatically call its destructor to release the singleton object static CGarbo Garbo; private: / / vector _ v; / / 1. The constructor is privatized, and the object Singleton () {} / / anti-copy Singleton (const Singleton&) = delete; Singleton& operator= (const Singleton&) = delete; / / 2 cannot be created at will. Declare a static Singleton object in the class, define this object in cpp / / ensure that there is only one unique object static Singleton* _ spinst; static mutex _ mtx;} globally; "C++ singleton pattern instance Analysis" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.