Key Points of C ++ Programming

Source: Internet
Author: User
Key Point 1: <iostream. h> or <iostream>?
Many C ++ programmers are still using <iostream. h> instead of using the updated standard <iostream> library.
What are the differences between the two? First, five years ago, we began to oppose the use of the. h symbol in the standard header.
File. It is not a good way to continue using outdated rules. In terms of functionality,
<Iostream> contains a series of templated I/O classes. On the contrary, <iostream. h> only supports characters.
Stream. In addition, the C ++ standard interface of the input/output stream has been improved in some subtle details. Therefore,
<Iostream> and <iostream. h> are different in terms of interfaces and execution. Finally, each group of <iostream>
Chengdu is declared as STL. However, the components of <iostream. h> are declared as global.
Because of these differences, you cannot confuse these two libraries in a program. As a kind of study
<Iostream> is generally used in new Code. However, if you are dealing with code written in the past
Inheritance can be used to continue to use <iostream. h> to maintain code consistency.
Key 2: notes when passing parameters through references
When passing parameters with references, it is best to declare the references as the const type. The benefit of doing so is: Tell
The program cannot modify this parameter. In the following example, function f () is the reference passed:

Void F (const Int & I );
Int main ()
F (2);/* OK */

This program passes a parameter 2 to F (). At runtime, C ++ creates a 2-type int
And pass its reference to F (). This temporary variable and Its Reference are created since F () is called.
And exists until the function returns. Is deleted immediately. Note: if we do not add
Const limitation, then function f () may change the value of its parameter, more likely the program produces unexpected
Action. So don't forget Const.
This key point also applies to user-defined objects. You can add references to temporary objects.
Const type:

Struct {};
Void F (const A & );
Int main ()
F (a (); // OK, the const reference of a temporary A is passed.

Key Aspect 3: comma separated expression
The comma-separated expression is inherited from C and used in the for-and while-loops. Of course, this
Rules are considered inintuitive. First, let's take a look at what is a comma separated expression.
An expression is composed of one or more other expressions separated by commas, for example:

If (++ X, -- y, Cin. Good () // three expressions
This if condition contains three expressions separated by commas. C ++ calculates each expression, but it is complete.
The result of the comma separated expression is the value of the rightmost expression. Therefore, only when cin. Good () returns
True indicates that the value of the IF condition is true. The following is another example:
Int J = 10;
Int I = 0;
While (++ I, -- J)
// Until J = 0, the loop ends. During the loop, I continuously auto-Increment
Key 4: Use the global object constructor to call the function before the program starts.
Some applications need to call other functions before the main program starts. Such as transition process functions and Registration
All functional functions must be called before the actual program runs. The simplest way is to use a Global Object
To call these functions. Because global objects are constructed before the main program starts, these functions
Will return results before Main. For example:
Class Logger
Logger ()
Activate_log (); // Note: Call the function you need to run first in the constructor.
Logger log; // a global instance
Int main ()
Record * prec = read_log (); // Translator's note: Read log file data
// .. Program code

The Global Object log is constructed before the main () operation, and the log calls the activate_log () function (). Slave
However, when main () is executed, it can read data from the log file.
Undoubtedly, memory management is the most complex and prone to bugs in C ++ programming. Direct Access
Asking about the original memory, dynamically allocating storage, and maximizing the efficiency of the C ++ command, you must do your best to avoid
Memory bugs.
Key 5: Avoid using pointers to functions in Complex Structures
The pointer to a function is one of the least readable syntax in C ++. Can you tell me what the following statements mean?

Void (* P [10]) (void (*)());
P is a "10 pointers pointing to one return void type and pointing to another with no return and no
Array of the computed functions ". This troublesome syntax is really hard to recognize, isn't it? You can actually simplify
The typedef statement is used to declare the function of the preceding statement. First, use typedef to declare
Pointer to a function without return or operation ":
Typedef void (* PFV )();
Then, declare "another pointer to a function that does not return and uses PFV ":
Typedef void (* pf_taking_pfv) (PFV );
Now, declare an array composed of 10 pointers above:
Pf_taking_pfv P [10];
Same effect as void (* P [10]) (void. But is this more readable?
Key 6: pointer to a member
A class has two basic types of members: function members and data members. Similarly, pointers to members are also
There are two types: pointer to a function member and pointer to a data member. Is not commonly used, because
Generally, it does not include public data members. It is used only to coordinate the structure (struct) and
The pointer to a member is one of the most incomprehensible structures in the C ++ syntax, but it is also the strongest in the C ++ syntax.
Big features. It allows you to call a function member of a class without having to know the name of the function. This
A very agile calling tool. Similarly, you can use a pointer to a data member to check and modify
You do not need to know the name of the member to change the data.
Pointer to a data member
Although at the beginning, the syntax of pointer to the member may confuse you a little bit, but you will soon issue
In fact, it is similar to a common pointer, but it is preceded by the "*" symbol and class name. For example:
Define a pointer to the int type:

Int * PI;
Define a data member pointing to an int type class:
Int A: * PMI; // PMI is a member of the int type pointing to Class.
You can initialize it like this:
Int num;
Int X;
Int A: * PMI = & A: num;
The code above declares an int-type num member pointing to Class A and initializes it as this Num
The Member address. By adding * to the front of PMI, you can use and change the value of the num member of Class:
A A1, A2;
Int n = A1. * PMI; // assign a1.num to n
A1. * PMI = 5; // assign 5 to a1.num
A2. * PMI = 6; // assign 6 to 6a2. Num.

If you define a pointer to Class A, you must use the-> * operator to represent the above operations.
A * pA = new;
Int n = pa-> * PMI;
Pa-> * PMI = 5;
Pointer to a function Member
It is composed of the Data Types returned by function members. The class name follows: symbol, pointer name, and function parameter.
Number list. For example, a pointer to a function member of Class A (this function returns the int type:

Int func ();
INT (A: * PMF )();

The above definition means that PMF is a pointer to the function member func () of Class A. In fact, this
A pointer is no different from a normal pointer to a function, but it contains the class name and:
. You can call this function in any place where * PMF is used.
Func ():
PMF = & A: func;
(A. * PMF) (); // call A. func ()
If you first define a pointer to an object, the above operation should be replaced by->:
A * pA = &;
(Pa-> * PMF) (); // call pa-> func ()
The pointers to function members should consider polymorphism. Therefore, when you call a virtual function member through a pointer
This call will be dynamically recycled. You cannot take the constructor of a class.
Number and the Destructor address.
Key Aspect 7. Avoid memory fragmentation
This often happens when your application runs because of its own defects.
Memory vulnerabilities leak the memory, and you repeatedly repeat your program periodically. The results can be imagined, and it will
Crash the system. But how can we prevent it? First, try to use less dynamic memory. In most cases
You may use static or automatic storage or STL containers. Second, allocate as much memory as possible instead
Only a small amount of memory is allocated at a time. For example, allocate the memory required by an array instance at a time, instead
Allocate memory for only one array element at a time.
Key Aspect 8: delete or delete []
The programmer has an absurd saying: when using Delete to replace Delete [] to delete the array type
For example:

Int * P = new int [10];
Delete P; // error, which should be: Delete [] P
The above program is completely incorrect. In fact, on a platform, use Delete instead of Delete []
Applications may not cause system crashes, but it is luck. You cannot guarantee that your application is not
Is compiled on another compiler and runs on another platform. Therefore, use Delete [].
Key 9. Optimizing member Arrangement
The size of a class can be changed as follows:

Int B;
Bool C;
}; // Sizeof (A) = 12

On my computer, sizeof (a) equals 12. This result may surprise you, because the total number of members of
The number is 6 bytes: 1 + 4 + 1 bytes. Where did the other 6 bytes come from? The compiler is behind each bool member.
Three fill bytes are inserted to ensure that each member is arranged in 4 bytes to facilitate the division. You can reduce
In the following way:

Struct B
Bool C;
Int B;
}; // Sizeof (B) = 8

This time, the compiler inserts only two bytes after member C. Because B occupies 4 bytes
However, it is arranged as a word, and the size of a and c is 1 + 1 = 2, and the addition of 2 bytes is just two
Key 10: Why is it dangerous to inherit a class without virtual destructor?
A class without virtual destructor means it cannot be used as a base class. For example, STD: string,
STD: complex, and STD: vector. Why inherit from a non-virtual destructor?
Class is dangerous? When you create a class that inherits from the base class
Both the needle and reference actually point to the object of origin. Because the Destructor are not virtual functions, when you delete
When such a class is used, C ++ does not call the Destructor chain. For example:

~ A () // not a virtual function
Class B: public a // error; A does not have a virtual destructor
~ B ()
Int main ()
A * P = new B; // It looks right
Delete P; // error. The destructor of B is not called.

Key Aspect 11: declare Nested classes with a friend class
When you declare a nested class with a friend class, put the friend class declaration behind the nested class declaration, instead

Int I;
Class B // nesting class declaration before
B (A & A) {a. I = 0 ;};
Friend Class B; // friend class declaration

If you place the Statement on the front of the declared nested class, the compiler will discard the other statements after the class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.