Based on the difference between Pointers and references

  • 2020-04-01 01:47:18
  • OfStack

Pointer with "*" and "->" Operator, the reference USES the "." operator, which of course is the surface difference.

      1. A reference must represent an object. There is no such thing as an empty reference. The pointer can be NULL. That is, the reference must have an initial value, not a pointer. So before using Pointers, you must test if it is null. References do not need to be tested.

      2. Pointers can be reassigned to point to another object. The reference always points to the object it first acquired:


string s1("Nancy");
string s2("Clancy");
string &rs = s1;      //Rs to s1.
string *ps = &s1;  //Ps to s1.
rs = s2;                 //Rs still stands for s1,
                             //But the value of s1 becomes Clancy.

ps = &s2;             //Ps is now pointing to s1,
                            //S1 doesn't change

      3. There are some cases where references are needed. For example, when implementing certain operators. The most common example is operator[]. This operator in particular must return something that can be considered an assignment object.

      4. Conclusion: when you know you need to point to something and will never change pointing to something else, or when you implement an operator whose syntax requirements cannot be met by Pointers, you should use references. Any other time, please use Pointers.


Related articles: