Over the past few days, I have reviewed the high quality C/C ++ programming guide and more effective C ++. I think the references and pointers in this Guide are well written, at the same time, I also found some summary written by others on the Internet and shared it with you.
Although both references and pointers can indirectly access another value, there are two important differences between them:
- A reference always points to an object. It is wrong to define a reference without initialization.
- The difference in the assignment action. Assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object. Once the reference is initialized, it always points to the same specific object.
★Similarities:
1. All are addresses;
The Pointer Points to a piece of memory, whose content refers to the address of the memory, and the reference is the alias of a piece of memory.
★Differences:
1. the pointer is an entity, and the reference is only an alias;
2. You do not need to unreference (*) when using a reference. The pointer must be unreferenced;
3. The reference can only be initialized once during definition, and will not be changed afterwards; the pointer will be variable;
Reference "from one end" ^_^
4. The reference has no const, the pointer has const, And the pointer of const is immutable;
5. The reference cannot be blank, and the pointer can be blank;
6. "sizeof reference" gets the size of the variable (object) to which it points, while "sizeof Pointer" gets the size of the pointer itself (the address of the variable or object to which it points;
Typeid (t) = typeid (T &) always true, sizeof (t) = sizeof (T &) always true, but when referencing as a member, the occupied space is the same as the pointer (no standard rule is found ).
7. the pointer and reference auto-increment (++) operations have different meanings;
★Contact
1. Reference is implemented using pointers inside the language (how to implement it ?).
2. For general applications, the reference is understood as a pointer and no serious semantic error is made. A reference is a pointer with limited operations (only content operations are allowed ).
★High quality C/C ++ programming guide 6.6
References are a concept in C ++. Beginners can easily confuse references with pointers. In the following program, n is a reference of M, and M is a referent ).
int m; int &n = m;
N is equivalent to M alias (nickname). Any operation on N is an operation on M. For example, someone named Wang xiaomao, whose nickname is "San Mao ". The reason for saying "three hairs" is actually to say three things to Wang xiaomao. Therefore, n is neither a copy of M nor a pointer to M. In fact, n is m itself.
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 ).
In the following example, K is initialized as a reference of I. Statement K = J cannot be changed to j Reference, but the value of K is changed to 6. Because K is an I reference, the value of I is also changed to 6.
Int I = 5; Int J = 6; Int & K = I; k = J; // The values of K and I are changed to 6;
The above program looks like playing a text game and does not reflect the value of reference. 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.
The following is a sample program for "value transfer. Since X in the func1 function is a copy of the external variable N, changing the value of X does not affect N, so the value of N is still 0.
void Func1(int x){x = x + 10;}int n = 0;Func1(n);cout << “n = ” << n << endl;// n = 0
The following is an example program for "pointer passing. Since X in the func2 function is a pointer to the external variable N, changing the content of this pointer will change the value of N, so the value of N is 10.
void Func2(int *x){(* x) = (* x) + 10;}⋯int n = 0;Func2(&n);cout << “n = ” << n << endl; // n = 10
The following is a sample program for "reference transfer. Since X in the func3 function is referenced by the external variable n, x and n are the same thing, changing X equals to changing N, so the value of N becomes 10.
void Func3(int &x){x = x + 10;}//...int n = 0;Func3(n);cout << “n = ” << n << endl; // n = 10
Comparing the above three examples, we will find that the nature of "Reference transfer" is like "pointer transfer", and the writing method is like "value transfer ". In fact, "reference" can be used to do anything "pointer". Why do we need to "reference"
This thing?
The answer is "Use appropriate tools for proper work ".
Pointers can operate on the memory without any constraints. Although pointers are powerful, they are very dangerous.
Like a knife, which can be used to cut trees, cut paper, manicure, and cut hair. Who dares to use it like this?
If you only need to borrow the "alias" of an object, use "Reference" instead of "Pointer" to avoid exceptions. For example, a person needs a proof that the seal was originally printed on the document. If he handed over the key to the seal, he would have obtained the right he did not have.
★Clause 1: differences between pointers and references
Pointers and references look completely different (pointers use operators '*' and '->', and references use operators '.'), but they seem to have the same functionality. Both pointer and Reference allow you to indirectly reference other objects. How do you decide when to use pointers and when to use references?
First, you must realize that the reference pointing to a null value cannot be used under any circumstances. A reference must always point to some objects. Therefore, if you use a variable and direct it to an object, but the variable may not point to any object at some time, you should declare the variable as a pointer, in this way, you can assign a null value to the variable. On the contrary, if the variable must point to an object, for example, your design does not allow the variable to be empty, then you can declare the variable as a reference.
"But please wait." You asked with suspicion, "What are the consequences of such code ?"
Char * Pc = 0; // set the pointer to null char & rc = * PC; // Let the reference point to a null value
This is very harmful and there is no doubt. The results will be uncertain (the compiler can generate some output, causing everything to happen) and should avoid the people who write such code unless they agree to correct the error. If you are worried that such code will appear in your software, you 'd better avoid using references completely, or else let better programmers do it. In the future, we will ignore the possibility that a reference points to a null value.
Because the reference will certainly point to an object, in C, the reference should be initialized.
String & RS; // error. The reference must be initialized strings ("xyings"); string & rs = s; // correct. RS has no such restriction on pointing to the S pointer. String * pS; // uninitialized pointer // valid but dangerous
The fact that there is no reference pointing to a null value means that the code to be referenced is more efficient than the pointer. Because you do not need to test its validity before using the reference.
Void printdouble (const double & rd) {cout <RD; // you do not need to test RD. It} // It must point to a double value. Instead, the pointer should always be tested, prevent empty: void printdouble (const double * PD) {If (PD) {// check whether it is null cout <* PD ;}}
Another important difference between a pointer and a reference is that a pointer can be re-assigned to point to another object. However, the reference always points to the specified object during initialization and cannot be changed later.
Strings1 ("Nancy"); strings2 ("Clancy"); string & rs = S1; // Rs reference S1 string * PS = & S1; // PS points to S1 rs = S2; // Rs still references S1 // but the value of S1 is "Clancy" PS = & S2; // PS now points to S2; // S1 has not changed
In general, you should use pointers in the following situations. First, you should consider the possibility of not pointing to any object (in this case, you can set the pointer to null ), second, you need to be able to point to different objects at different times (in this case, you can change the pointer ). If you always point to an object and it does not change its direction once it points to an object, you should use references.
Another case is that when you reload an operator, you should use references. The most common example is the operator []. A typical use of this operator is to return a target object, which can be assigned a value.
Vector <int> V (10); // create an integer vector (vector) with a size of 10 // vector is a template in the Standard C library (see article 35) V [5] = 10; // the target object to be assigned is the value returned by the operator [].
If the operator [] returns a pointer, the next statement must be written as follows:
*v[5] = 10;
However, this will make V look like a vector pointer. Therefore, you will choose to let the operator return a reference. (This is an interesting exception. Refer to Clause 30)
When you know that you must point to an object and do not want to change its direction, or when you overload operators and prevent unnecessary semantic misunderstanding, you should not use pointers. In other cases, pointer should be used.