In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the pits of C++". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Now please follow the editor's train of thought slowly and deeply. Let's study and learn about the pits of C++.
1. String concatenation of string, resulting in coredump
The core of the problem is line 9, which actually compiles because x + "-" is converted to char*, and then superimposed with to_string to cause BUG.
2. Delete the iterator of map
Map deletes an element, which is usually done through the erase () function, but note that if we pass in an iterator as an argument to erase to delete the element pointed to by the current iterator, the iterator will be invalidated after deletion, resulting in undefined behavior.
The correct way to use it is to receive the return value of erase () and have iterator point to the next element of the deleted element or end ().
For (auto iter = m.begin (); iter! = m.end (); iter++) {if (...) Iter = m.erase (iter);}
But there is still an error in the above code, because if deletion is triggered, iter will point to the next element in the next loop, so the correct way to write it is:
For (auto iter = m.begin (); iter! = m.end ();) {if (...) {iter = m.erase (iter); continue;} else {iter++;}}
3. Performance problems of stringstream
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
After emptying stringstream is clear, leave it empty.
Stringstream is slower than snprintf in any case.
Memset is a slow function, preferring to create new objects.
The above test results are single-threaded and changed to multi-threaded, which is also true.
Str+ = "a", which is much more efficient than str = str+ "a", which creates new objects.
4. Smart pointer (shared_ptr) usage attention
4.1 initialization using make_shared whenever possible
Improve performanc
Std::shared_ptr spw (newWidget)
Memory needs to be allocated twice. Each std::shared_ptr points to a control block that contains the reference count of the object being pointed to, among other things. The memory of this control block is allocated in the constructor of std::shared_ptr. So using new directly requires a block of memory to be allocated to Widget and a block of memory to be allocated to the control block.
Autospw = std::make_shared ()
One distribution is enough. This is because std::make_shared requests a separate block of memory to hold both Widget objects and control blocks. This optimization reduces the static size of the program because the code contains only one memory allocation call, and this speeds up the execution of the code because memory is allocated only once. In addition, the use of std::make_shared eliminates some of the information that the control block needs to record, which potentially reduces the total memory footprint of the program.
Abnormal security
ProcessWidget (std::shared_ptr (new Widget), / / potential resource leakage computePriority ())
There is a risk of memory leakage in the above code, and the execution of the above code is divided into three steps:
1. New Widget
2. Shared_ptr construction
3. ComputePriority
The compiler does not need to generate code in this order, but "new Widget" must be executed before the constructor of the std::shared_ptr is called. If the compiler produces the following sequence code:
1. New Widget
two。 Execute computePriority.
3. Executes the constructor of the std::shared_ptr.
If the program encounters an exception while executing step 2:computePriority, the Widget dynamically allocated in the first step will be leaked because it will never be stored in the shared_ptr that begins to manage it in step 3.
4.2 Smart pointer conversion such as parent class
Naked pointers are allowed in C++, so the conversion method between bare pointers is the same as that of C language pointers. Smart pointer conversion can not be done by the above methods, but must be converted through the conversion function provided by the library. The method of clocking 11 is: boost::dynamic_pointer_cast in std::dynamic_pointer_cast;boost
# include # include class Base {public: Base () {} virtual ~ Base () {}}; class D: public Base {public: d () {} virtual ~ D () {}}; int main () {
/ / method 1: first initialize the subclass smart pointer, and then call dynamic_pointer_cast to convert the base class smart pointer object
Std::shared_ptr D1 = std::make_shared (); std::shared_ptr b1 = std::dynamic_pointer_cast (D1)
/ / method 2: first new the pointer of subclass D, and then call the constructor of shared_ptr to initialize the smart pointer of the base class
Std::shared_ptr b2 = shared_ptr (new D ()); return 0;}
Conclusion
Both mode 1 and mode 2 can realize that the intelligent pointer of the base class can point to the subclass, but it is recommended to use mode 1 to construct the intelligent pointer by std::make_shared, and then convert it.
5. Security search method of map
In other words, elements are created (and not necessarily initialized), so when the business logic wants to find them, use find honestly, otherwise dirty data will be written.
6. Pointer construction of string
The way std::string is constructed, in addition to being similar to other sequential containers, provides three additional construction methods:
String s (cp, n): s is a copy of the first n characters in the array pointed to by cp, which should contain at least n characters
String s (S2, pos2): s is a copy of the string S2 character starting with the subscript pos2. If pos2 > s2.size (), the behavior of the constructor is undefined
String s (S2, pos2, len2): s is the len2 character copy of string S2 starting with the subscript pos2. If pos2 > s2.size (), the behavior of the constructor is not defined. Regardless of the value of len2, the constructor copies at most s2.size ()-pos2 characters
Std::string does not provide the construction of string (cp, pos2, len2). If this method is used in the code, the array pointed to by cp will eventually be constructed into a string, and then string (S2, pos2, len2) will be called.
The reason why string (cp, pos2, len2) is not provided is that it is prone to problems when constructing in this way. Cp is a pointer, and when you usually use it, you can get its array length and check the incoming parameters; if you pass two parameters, it is easy to cross the line.
7. Variable initialization
Variable initialization is always correct, regardless of whether or not the value will be modified later. In particular, built-in types such as int are easy to ignore initialization in classes or struct, making variables random, resulting in unpredictable errors. Please initialize the variable! Please initialize the variable! Please initialize the variable!
Thank you for your reading. The above is the content of "what is the pit of C++?" after the study of this article, I believe you have a deeper understanding of what is the pit of C++. The specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.