Talk briefly about the difference between Pointers and references in C++

  • 2020-05-17 06:07:19
  • OfStack

Pointers and references are two very important concepts in C++. They used to be very similar in function, that is, they both refer to an object indirectly. So when should we use Pointers and when should we use references?

1. Never use a reference to a null value. A reference must always point to an object, so when you decide to use a variable to point to an object, but the object may point to control at some point in time, you must declare the variable as a pointer type, not a reference! When you are sure that the variable always refers to an object, you can declare the variable as a reference type.


char *str=0; // Set the pointer to null 
char &s=*str; // Have the reference point to a null value 

You should avoid the mistakes above!

2. Because the reference must always point to an object, the reference must be initialized in C.


string& rs;   //  The misreference must be initialized 
string s("xyzzy");
string& rs = s; //  correct  rs Point to the s

Pointers have no such limitation:


string *ps; //  not   In the early   beginning   the   the   Refers to the   The needle 
      //  us   method   but   danger   risk 

3. The fact that there is no reference to a null value means that code using a reference is more efficient than code using a pointer, because you don't need to test the validity of the reference before using it.


void printDouble(const double& rd)
{
   cout << rd;  //  No need to test rd, it 
}          //  Sure to 1 a double value 

Instead, the pointer should always be tested to prevent it from being null:


void printDouble(const double *pd)
  {
    if (pd) {  //  Check for NULL
      cout << *pd;
    }
  }

4. Another important difference between a pointer and a reference is that the pointer can be reassigned to point to a different object, but the reference always points to the object specified at the time of initialization and cannot be changed later.


string s1("Nancy");
  string s2("Clancy");
  string& rs = s1; // rs  reference s1
  string *ps = &s1; // ps  Point to the s1
  rs = s2; // rs  Still reference s1,
      //  but s1 The value of theta is now zero 
      // "Clancy"
  ps = &s2; // ps  Now point to the s2;
       // s1  There is no change 

5. You should use references when overloading an operator. The most common example is the overloading operator []. This operator is typically used to return a target object that can be assigned a value.

In general, you should use Pointers in the following situations:

1 is that you allow for the possibility of not pointing to any object, in which case you can set the pointer to null;

Two is that you need to be able to point to different objects at different times, in which case you can change the pointer.

If you always point to one object and don't change the point once you point to one object, you should use a reference.


Related articles: