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/02 Report--
This article mainly explains "what C++ traps and tricks there are". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn what C++ traps and routines there are!
# I. introduction
C++ is not only a widely used system-level programming language, but also a high-performance back-end standard development language. Although C++ is powerful, flexible and ingenious, it is an expert language that is easy to learn and difficult to master. Even veteran drivers are easy to fall into all kinds of traps. Combined with the work experience and learning experience of the account owner, this paper briefly introduces some advanced features of C++ language, explains and clarifies some common misunderstandings, and summarizes the places that are easy to make mistakes. I hope this can enhance everyone's understanding of C++ language, reduce programming errors and improve work efficiency.
# II. Traps
# # 1. Global variables are used in my program, why does the process exit inexplicably core?
The global variables defined by Rule:C++ in different modules (source files) do not guarantee the construction order, but ensure that the global variables defined in the same module (source files) are constructed in the order in which they are defined and destructed in the opposite order.
Our program defines the global variables X and Y in turn in a.cpp.
According to the rule: X is constructed first, Y is constructed later; when the process stops execution, Y is deconstructed first, and X is destructed later; but if the deconstruction of X depends on Y, then core can happen.
* * conclusion * *: if global variables have dependencies, put them in the same source file definition and define them in the correct order to ensure that the dependencies are correct rather than defined in different source files; for individual items in the system, singleton dependencies should also pay attention to this problem.
# # 2. Pit in pit: std::sort ()
It is believed that at least 50% of the programmers who have worked for more than 5 years have been cheated by it. I have heard countless sad stories, "Saint Seiya", "Xianjian", and other people's project "Aixiaochu". Some people fell into the pit, and the program ran for a few days with an inexplicable and strange Crash on his face.
The sort algorithm has strong constraints on the comparison function and cannot be mishandled. If you want to use it, you must provide your own comparison function or function object. You must figure out what is meant by "strict weak sorting" and meet the following three characteristics:
1. Non-reflexivity
two。 Asymmetry
3. Transitivity
Try to sort the index or pointer, not the object itself, because swapping (copying) objects is more expensive than swapping pointers or indexes if the object is large.
# # 3. Pay attention to operator short circuit
Consider the logic that players refresh to the client by returning blood to blue (magic). Players return a little bit of blood every 3 seconds, and players return a little bit of blue every 5 seconds, and the return of blue blood uses a common protocol to notify the client, that is, whenever there is a return of blood or blue, it is necessary to notify the client of the new health and magic value.
The player's heartbeat function heartbeat () is called circularly in the main logic thread.
````C++ void GamePlayer::Heartbeat () {if (GenHP () | | GenMP ()) {NotifyClientHPMP ();}} ```
If GenHP returns blood, true is returned, otherwise false; does not necessarily return blood every time GenHP is called, depending on whether the 3-second interval is reached.
If GenMP returns blue, true is returned, otherwise false; does not necessarily return blood every time GenMP is called, depending on whether the 5-second interval is reached.
The actual operation found that the logic of returning blood to blue is wrong. Word Ma, it turns out that the operator is short-circuited. If GenHP () returns true, then GenMP () will not be called, and the opportunity to return blue may be lost. You need to modify the program as follows:
````C++ void GamePlayer::Heartbeat () {bool hp = GenHP (); bool mp = GenMP (); if (hp | | mp) {NotifyClientHPMP ();}} ```
Logic has the same problem as (& &) and logic or (| |). If (a & b) will not be evaluated if the expression of an evaluates to false,b.
Sometimes we write code like if (ptr! = nullptr & & ptr- > Do ()), which takes advantage of the syntax feature of operator short circuit.
# # 4. Don't let the cycle stop.
```C++ for (unsigned int i = 5; I > = 0;-- I) {/ /...} ```
The program came here, WTF? You can't stop at all? The question is simple: unsigned is always > = 0. Is it true that ten thousand horses are galloping in your heart?
It's easy to solve this problem, but sometimes this kind of mistake is not so obvious, and you need a brighter cover.
# # 5. Beware of crossing the line.
Memcpy,memset has strong restrictions and can only be used with POD structures and cannot be used on stl containers or classes with virtual functions.
A class object with a virtual function will have a pointer to the virtual function table, and memcpy will break the pointer to.
To execute memset/memcpy for non-POD, I will give you four words for free: * * seek your own happiness * *
# # 6. Memory overlap
When copying memory, if src and dst overlap, you need to use memmov instead of memcpy.
# # 7. Understanding user stack space is limited.
You cannot define temporary objects that are too large on the stack. In general, the user stack is only a few megabytes (the typical size is 4m, 8m), so the objects created on the stack cannot be too large.
# # 8. When formatting a string with sprintf, the type and symbol should match strictly
Because the function implementation of sprintf fetches parameters from the stack according to the format string, any inconsistency may cause unpredictable errors; / usr/include/inttypes.h defines cross-platform formatting symbols, such as PRId64 to format int64_t
# # 9. Replace the non-secure version with the secure version of the c standard library (marked with n)
For example, replace strcpy with strncpy, replace sprintf with snprintf, replace strcat with strncat, and replace strcmp,memcpy with strncmp (dst, src, n). Make sure that [dst,dst+n] and [src, src+n] have valid virtual memory address space. In a multithreaded environment, to replace the unsafe version (_ r version) with the safe version of the system call or library function, keep in mind that standard c functions such as strtok,gmtime are not thread safe.
# # when traversing and deleting STL containers, be careful of iterator failure
Vector,list,map,set and others have different ways of writing:
Vector,list,map,set and others are written differently: ````C++ int main (int argc, char * argv []) {/ / vector traversal to delete std::vector v (8); std::generate (v.begin (), v.end (), std::rand); std::cout = max_num) throw out_of_bound ()
If it is an unsigned integer, you only need to judge if (index > = max_num). Do you agree?
# # it's good to use int,long for integers, but you need to be very careful to use short,char to prevent overflow
In most cases, it's good to use int,long. Long is generally equal to machine word length, long can be put directly into registers, and hardware processing is faster.
In many cases, we want to use short,char (8-bit integer) to reduce the size of the structure. However, due to byte alignment, it may not be really reduced, and the number of integer digits of 2 bytes is too small, which accidentally overflows, which requires special attention.
Therefore, unless in db, network, which is very sensitive to storage size, we need to consider whether to replace int,long with short,char.
# VI. Expansion
# # learn about the advanced features of C++
Templates and generic programming, union,bitfield, pointers to members, placement new, explicit destructions, exception mechanisms, nested class,local class,namespace, multiple inheritance, virtual inheritance, volatile,extern "C", etc.
Some advanced features are only used under certain circumstances, but many skills do not weigh on you, and you still need to accumulate and understand them, so that you can take tools from your knowledge base to deal with it when the demand arises.
# # learn about the new standard of C++
Pay attention to new technologies, such as centering 11, 14, 17, lambda, right-value references, move semantics, multi-thread libraries, etc.
It has been 13 years since the introduction of the standard cymbal 98and11, and the idea of programming language has been greatly developed in the past 13 years. The new standard of cantiledge 11 has absorbed many new features of other languages. Although the new standard of cymbals 11 mainly supports new features by introducing new libraries, and there are few changes in core languages, the new standard still introduces core grammatical changes such as move semantics. Every CPPer should understand the new standard.
# # OOD Design principles are not nonsense
+ six principles of design pattern (1): single responsibility principle
+ six principles of design pattern (2): Richter substitution principle
+ six principles of design pattern (3): the principle of dependency inversion
+ six principles of design pattern (4): interface isolation principle
+ six principles of design pattern (5): Demeter's rule
+ six principles of design pattern (6): opening and closing principle
# # be familiar with common design patterns, learn and use them, and don't copy them mechanically
Deified design patterns and anti-design patterns are not scientific attitudes, design patterns are a summary of software design experience and have a certain value; GOF books on each design pattern, use special paragraphs to talk about its application scenarios and applicability, limitations and defects, in the case of a correct assessment of gains and losses, is encouraged to use, but obviously, you need to accurately get to her first.
Thank you for your reading. The above is the content of "what are the traps and tricks of C++". After the study of this article, I believe you have a deeper understanding of the traps and tricks of C++. The specific use of the situation also needs to be verified by 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.