Differences between C ++ pointers and references

Source: Internet
Author: User

Today, we can see the C ++ pointer. By the way, let's look at the difference between the pointer and the reference ..

1. First, the reference must be initialized, And the pointer does not have. So if you use a variable and point it to an object, but the variable may not point to any object at some time, this should be declared as a pointer; on the contrary, if you confirm that the variables used are not allowed to be null at any time during design, you should declare the variables as references. Because the reference does not point to a null valueCodeEfficiency is higher than pointer.

String & S; // error. The reference must be initialized.

String STR = "123456 ";

String & s = STR; // point S to the STR variable

2. Difference in legitimacy: you do not need to test its legitimacy before using the reference, but the pointer is always tested to prevent it from being empty.

3. Modification difference: the reference cannot be modified after initialization, And the pointer can modify the object to which it points.

4. Application: the pointer should be used in the following situations:

(1) When there may be variables that do not point to any object, Use Pointer variables.

(2) Use Pointer variables when pointing to different objects at different times.

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.