Pointer and reference comparison

Source: Internet
Author: User

Using reference) and pointers can indirectly access another value, but there are two important differences between them.

1. Reference always points to an object: it is wrong to define the reference without initialization.

2. Differences in Value assignment: assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object. Once the reference is initialized, it always points to the same specific object, which is why the reference must be initialized at the definition ).

The following two differences are illustrated:

Example 1:

#include <iostream>using namespace std;void main() {    int ival = 1024, ival2 = 2048;    int *pi = &ival, *pi2 = &ival2;    pi = pi2;    cout<<ival<<" "<<ival2<<endl;    cout<<pi<<" "<<pi2<<endl;}

After the assignment, the value of the ival object pointed to by pi is 1024 and remains unchanged. The assignment operation modifies the value of the pi pointer so that it points to another object, pi and pi2 point to the same address!

Example 2:

#include <iostream>using namespace std;void main() {    int ival = 1024, ival2 = 2048;    int &ri = ival, &ri2 = ival2;    ri = ri2; // assigns ival2 to ival    cout<<ival<<" "<<ival2<<endl;    cout<<&ri<<" "<<&ri2<<endl;}

This assignment operation modifies the ival object referenced by ri, not the reference itself. After the value assignment, the value of ival is the same as that of ival2, Which is 2048, but the two references still point to the original associated object ri and ri2 addresses respectively). At this time, the values of these two objects are equal.


This article is from my study notes blog, please be sure to keep this source http://6924918.blog.51cto.com/6914918/1270676

Related Article

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.