How does C++ encapsulate messy code
This article introduces the knowledge of "how C++ encapsulates chaotic code". 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!
Encapsulate messy code instead of spreading them Reason (reason)
Messy code is easy to hide errors and difficult to write. A good interface will be easy to use and secure. Confusingly, low-level code produces a lot of programs like the following example.
Example (example) int sz = 100 for * p = (int*) malloc (sizeof (int) * sz); int count = 0. For (;) {/ /. Read an int into x, exit loop if end of file is reached... / /... Check that x is valid... If (count = = sz) p = (int*) realloc (p, sizeof (int) * sz * 2); p [count++] = x; / /.}
This is a low-level, lengthy, error-prone code. For example, we forgot to check for memory exhaustion. As an alternative, we can use vector:
Vector vt. Reserve; / /. For (int x; cin > > x;) {/ /. Check that x is valid... V.push_back (x);} translator's note: vector can also provide perfect memory management while ensuring high performance.
Note (Note)
Standard libraries and GSL can serve as examples of this principle. For example, instead of directly using arrays, unions, type conversions, and dealing with life cycle, gsl::owner, and so on, it is better to use higher-level abstracted and implemented functions such as vector,span,lock_guard and future provided by the standard library. The designers and developers of the standard library have more time and experience than we do. Similarly, we can and should design and implement proprietary libraries, rather than letting users (usually ourselves) constantly challenge low-level code. This is another statement that forms part of the principles of these guidelines.
Enforcement (implementation recommendations)
Find "messy code", such as complex pointer operations or type conversions other than implementing abstractions.
This is the end of the content of "how C++ encapsulates chaotic code". 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!