C ++ high-quality programming
For C ++ programming, developers can write two paragraphs, but it is still relatively small to write high-quality code. I am also a learner. This article is usually used to learn logs. Update at any time ......
1. Const data members are constants only within the lifetime of an object, but they are variable for the entire class,
Because the class can create multiple objects, the values of the const data members of different objects can be different.
Chapter 2 Function Design
1. Two elements of a function interface are parameters and return values.
Avoid too many parameters in a function, and set the number of parameters to less than 5.
Do not use parameters with uncertain types or numbers.
2. Check the parameter validity at the "ENTRANCE" of the function body.
Many program errors are caused by Invalid parameters. We should fully understand and correctly use assert to prevent such errors.
Assert is a macro that only works in the debug version. It is used to check the situation where "no" occurs.
Assert (pvto! = NULL) & (pvfrom! = NULL ));
3. Check the correctness and efficiency of the Return Statement at the "exit" of the function body.
If the return statement is not well written, the function either fails or is inefficient.
(1) The return statement cannot return "Pointer" or "Reference" pointing to "stack memory" because the function body is automatically destroyed when it ends.
4. Comparison between references and pointers
Some referenced rules are as follows:
(1) The reference must be initialized at the same time (the pointer can be initialized at any time ).
(2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).
(3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time)
The main function of the reference is to pass the parameters and return values of the function.
In C ++, function parameters and return values are transmitted in three ways: value transfer, pointer transfer, and reference transfer.
5. pointers can operate on the memory without any constraints. Although pointers are powerful, they are very dangerous.
Chapter 4 Memory Management
1. There are three memory allocation methods:
(1) distribution from the static storage area.
The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.
(2) create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released.
Stack memory allocation computation is built into the processor's instruction set, which is highly efficient, but the memory capacity allocated is limited.
(3) allocate from the stack, also known as dynamic memory allocation. When the program is running, use malloc or new to apply for any amount of memory,
The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by us. It is very flexible to use, but the problem is also the most.
2. Common memory errors and Countermeasures
(1) The Memory Allocation fails, but it is used.
A common solution is to check whether the pointer is null before using the memory.
If the pointer P is a function parameter, use assert (P! = NULL.
If you use malloc or new to apply for memory, you should use if (P = NULL) or if (P! = NULL.
(2) Although the memory allocation is successful, it is referenced before initialization.
Therefore, no matter which method is used to create an array, do not forget to assign the initial value. Even the zero value cannot be omitted, so do not bother.
(3) The memory has been allocated successfully and initialized, but the operation has crossed the memory boundary.
(4) forget to release the memory, causing memory leakage.
A function containing such errors loses a piece of memory every time it is called. Dynamic Memory application and release must be paired,
The usage of malloc and free in the program must be the same, otherwise there must be an error (the same applies to new/delete ).
(5) release the memory but continue to use it.
(1) The object calling relationship in the program is too complex, so it is difficult to figure out whether an object has been released
At this time, we should re-design the data structure to fundamentally solve the chaos of Object Management.
(2) The Return Statement of the function is incorrect. Be sure not to return the "Pointer" or "Reference" pointing to "stack memory ",
This is because the function body is automatically destroyed when it ends.
(3) After the memory is released using free or delete, the pointer is not set to null. As a result, a "wild pointer" is generated ".
3. After applying for memory with malloc or new, check whether the pointer value is null immediately. Prevents the use of memory with NULL pointer values.
Do not forget to assign initial values to arrays and dynamic memory. Avoid using uninitialized memory as the right value.
Avoid overrunning the subscript of an array or pointer, especially when "more than 1" or "Less 1" is performed.
Dynamic Memory application and release must be paired to prevent memory leakage.
After the memory is released with free or delete, the pointer is immediately set to null to avoid "wild pointer ".
4. Comparison between pointers and Arrays
In C ++/C Programs, pointers and arrays can be replaced in many places.
An array is either created in a static storage area (such as a global array) or on a stack. The array name corresponds to (rather than pointing to) a piece of memory.
A pointer can point to any type of memory block at any time, and its feature is "variable". Therefore, we often use pointers to operate dynamic memory.
Char * P = "world"; the pointer P points to the constant string "world" (in the static storage area with the content of World). The content of the constant string cannot be modified.
In terms of syntax, the compiler does not think that the statement P [0] = 'X' is inappropriate, but this statement attempts to modify the content of the constant string and causes a running error.
5. The C ++/C language cannot know the memory capacity referred to by the pointer unless you remember it when applying for memory.
Note: When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type.
6. How does the pointer Parameter Pass the memory?
If the function parameter is a pointer, do not expect this pointer to apply for dynamic memory.
7. The Compiler always needs to make a temporary copy for each parameter of the function. The copy of the pointer parameter P is _ p, and the compiler makes _ p = P.
If the program in the function body modifies the content of _ p, the content of parameter P is modified accordingly. This is why pointers can be used as output parameters.
In this example, _ P applied for a new memory, but changed the memory address indicated by _ p, but P was not changed at all. So the getmemory Function
It cannot output anything. In fact, each execution of getmemory will leak a piece of memory, because the memory is not released with free.
8. If you have to use pointer parameters to request memory, you should use "pointer to Pointer" instead.
Because the concept of "pointer to Pointer" is not easy to understand, we can use function return values to transmit dynamic memory.
It is emphasized that the return statement should not be used to return the pointer pointing to the "stack memory", because the function will automatically die when it ends.
9. After the pointer P is found free, its address remains unchanged (not null), but the memory corresponding to the address is junk, and p becomes a "wild pointer ".
If P is not set to null at this time, it is mistaken that p is a valid pointer.
10. Will dynamic memory be automatically released?
(1) If the pointer disappears, it does not mean that the memory it refers to will be automatically released.
(2) The memory is released, which does not mean that the pointer will die or become a null pointer.
11. "wild pointer" is not a null pointer, but a pointer to "junk" memory.
There are two main causes of "wild pointer:
(1) pointer variables are not initialized. When a pointer variable is created, it does not automatically become a null pointer. Its default value is random,
It gets angry. Therefore, the pointer variable should be initialized at the same time when it is created, either set the pointer to null or set it to direct to the legal memory.
(2) After the pointer P is free or deleted, It is not set to null, which makes people mistakenly think P is a valid pointer.
(3) pointer operations go beyond the scope of variables.
12. Why New/delete?
1. malloc and free are standard library functions in C ++/C, and new/delete are operators in C ++.
2. For non-Internal data objects, the use of maloc/free alone cannot meet the requirements of dynamic objects. Object
The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct.
13. What should I do if the memory is exhausted?
If a large enough memory block cannot be found when applying for dynamic memory, malloc and new will return a null pointer,
An error occurred while declaring the memory application. There are usually three ways to handle the "memory depletion" problem.
(1) judge whether the pointer is null. If yes, use the return statement to terminate the function immediately.
(2) judge whether the pointer is null. If yes, use exit (1) to terminate the entire program.
(3) set exception handling functions for new and malloc.
14. int * P = (int *) malloc (sizeof (INT) * length );
If P is a null pointer, no matter how many times the free P operation will fail. If P is not a null pointer, free
Two consecutive operations may cause program running errors.
Int * P2 = new int [length]; because new has built-in sizeof, type conversion, and type security check functions.
15. My lessons are as follows:
(1) The more you are afraid of pointers, the more you need to use pointers. If pointer is not used correctly, it is definitely not a qualified programmer.
(2) You must develop the habit of gradually tracing programs using the debugger. Only in this way can you discover the essence of the problem.
Chapter 2 advanced features of C ++ Functions
1. Compared with functions in C, C ++ adds four new mechanisms: overloaded, inline, const, and virtual.
The overload and inline mechanisms can be used for both global functions and class member functions. The const and virtual mechanisms are only used for class member functions.
2. Features of member functions being overloaded:
(1) the same range (in the same class );
(2) The function name is the same;
(3) parameters are different;
(4) virtual keywords are optional.
Override refers to the function of a derived class that overwrites the base class function. The features are as follows:
(1) different scopes (located in the derived class and the base class respectively );
(2) The function name is the same;
(3) The parameters are the same;
(4) basic functions must have virtual keywords.
3. Operator Overloading
In C ++, operators can be added to the operator keyword to represent functions, which are called Operator overloading.
Complex add (const complex & A, const complex & B );
Complex operator + (const complex & A, const complex & B );
The difference between an operator and a common function is that for a common function, the parameter appears in parentheses, and for an operator, the parameter appears on the left and right.
4. function inline
C ++ supports function inline to improve the function execution efficiency (speed ).
The member functions defined in the class declaration will automatically become inline functions.
Inline is at the cost of code expansion (replication). It only saves the overhead of function calls and improves the function execution efficiency.
Every call to an inline function must copy the code, which will increase the total amount of code in the program and consume more memory space.
Chapter 2 class constructor, destructor, and assignment function
1. Based on experience, many program errors that are hard to detect are caused by the failure to correctly initialize or clear variables, and initialization and cleanup are easily forgotten.
Chapter 2 other programming experience
1. The greater charm of const is that it can modify the parameters, return values, and even the definition body of a function.
2. For input parameters of non-Internal data types, the "value transfer" method should be changed to "const reference transfer" to improve efficiency.
For example, change void func (A) to void func (const A & ).
For internal data type input parameters, do not change the "value transfer" method to "const reference transfer ". Otherwise, it cannot achieve the goal of improving efficiency,
This reduces the comprehensibility of functions. For example, void func (int x) should not be changed to void func (const Int & X ).
3. Any function that does not modify data members should be declared as const type.
4. variables (pointers and arrays) should be initialized in time after they are created to prevent the uninitialized variables from being used as the right value.