Differences between references and pointers
References use the "." operator and pointers use the "*" and "->" operators, which are the basic and most familiar differences between the two.
First, there is no so-called null reference. A reference must always represent an object. Therefore, C ++ requires that the references must have an initial value:
String & rs; // error! References must be initialized
String s ("xyzzy ");
String & rs = s; // No problem. rs points to s.
However, pointers does not have such restrictions, although there are great risks:
String * ps; // uninitialized pointer, valid, but highly risky
Although C ++ does not have such restrictions, it is best to initialize a pointer when declaring it to avoid the occurrence of a wild pointer.
The following situations are also not allowed and should be taboo:
Char * pc = 0; // set pointer to null
Char & rc = * pc; // Let references represent the return value of null pointer
This is harmful, and the result is unpredictable (C ++). This is not defined, and the compiler can generate any possible output. So,
We will never consider the possibility that "reference is null.
The above facts mean that using reference may be more efficient than using pointer. This is because you do not need to test its validity before using reference:
Void printDouble (const duble & rd)
{
Cout <rd; // No need to test rd. It must represent a double
}
Void printDouble (const double * pd)
{
If (pd) // check whether it is null pointer
{
Cout <* pd;
}
}
Second, another important difference between pointers and references is that pointers can be re-assigned to point to another object, but references always point to (representing) the object it initially obtained:
String s1 ("Nancy ");
String s2 ("Clancy ");
String & rs = s1; // rs represents s1
String * ps = & s1; // ps indicates s1
Rs = s2; // rs still represents s1, but the value of s1 is now "Clancy"
Ps = & s2; // ps is now directed to s2, and s1 remains unchanged
In other cases, you also need to use references. For example, when you implement some operators, the most common example is operator []. This operator must particularly return something that "can be regarded as an assignment value assignment object:
Vector V (10); // generates an int vector with a size of 10.
V [5] = 10; // The Value assignment object of assignment is the return value of operator []
Therefore, you should select references when you know that you need to point to something, and never change to other things, or when you implement an operator and its syntax requirements cannot be fulfilled by pointers. Use pointers at any other time.