The difference between a reference and a pointer

Source: Internet
Author: User

Instead of defining a new variable, the reference is to re- alias an already defined variable. Features of the reference:
    1. Multiple variables can refer to a variable
    2. The reference must be initialized
    3. References can only be referenced once at initialization time and cannot be changed to refer to other variables.
const Reference void Test ()    { int d1 = 4;           const  int  &  d2  =  d1 D1 = 5; //D1 change The value of D2 will also change. //D2 = 6; Error! cannot assign a value to a constant (the amount that cannot be modified)   const int d3 = 1; const int & d4 = d3; //int&d5 = D3; const int & d6 = 5; // constants have constancy, only regular references can reference constants   double   d7  = 1.1; //int& d8 = D7;  //Error! D7 Yes Yes d7 d8 // that D8 is referring to This is a temporary variable with constancy, so you cannot assign a value. const int & d9 = D7;     }  Differences and linkages between references and pointers
    1. A reference can only be initialized once at the time of definition, and cannot be changed to point to another variable (mindedness), and the value of a pointer variable is variable.
    2. The reference must point to a valid variable, and the pointer can be empty.
    3. sizeof pointer objects and reference objects do not have the same meaning. sizeof refers to the size of the variable that is pointed to, and the sizeof pointer is the size of the object address.
    4. Pointers and reference self-increment (+ +) self-subtraction (--) have different meanings.
    5. In contrast, a reference is more secure than a pointer.
To summarize:pointers are more flexible than references, but they are also more dangerous. Be sure to check that the pointer is empty when using the pointer. The address indicated by the pointer is preferably set to 0 after release, otherwise there may be a wild pointer problem.

The difference between a reference and a pointer

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: info-contact@alibabacloud.com 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.