C ++: Differences and relationships between references and pointers, and issues that should be paid attention to when using common references.

Source: Internet
Author: User

C ++: Differences and relationships between references and pointers, and issues that should be paid attention to when using common references.
What is reference?A reference is to create an alias for a variable, but the variable is still the original variable and has not been redefined. For example:

 1 #include<iostream> 2 using namespace std; 3   4   5 int main() 6 { 7       int a = 10; 8       int& n = a; 9       cout<<a<<endl;10       cout<<n<<endl;11       cout<<&a<<endl;12       cout<<&n<<endl;13  14       return 0;15 }

 

The program runs as follows:

 

 

We can see that the reference (alias) n of variables a and a points to the same space, in addition, alias n does not create a new variable. When referencing it, we should pay attention to the following issues:
1. A variable can have multiple aliases. 2. the reference must be initialized. 3. the reference can only be referenced once during variable initialization, and other variables cannot be referenced later (this is almost impossible to reference other variables, but I cannot)
Regular referenceNow we know what a reference is, and a common reference is a reference that is very prone to errors. The following code is used:
1 int main () 2 {3 int d1 = 4; 4 const int & d2 = d1; 5 d1 = 5; // Changes the d2 value as well. 6 // d2 = 6; // you cannot assign 7 const int d3 = 1 to a constant (the amount cannot be modified); 8 const int & d4 = d3; 9 // int & d5 = d3; 10 const int & d6 = 5; // constant is constant. Only the constant occurrence can lead to the constant 11 double d7 = 1.1; 12 // int & d8 = d7; // d7 is double type, d8 is int, when d7 is assigned to d8, a temporary variable 13 is generated. // That is to say, d8 leads to a temporary variable with a regular nature, so it cannot be assigned a value. 14 const int & d9 = d7; 15 return 0; 16}
From the above code, we can know the issues that should be paid attention to when referencing const. References can be used as function parameters or return values, but what should we pay attention to when using them? 1. When you reference a function as a parameterWhen passing parameters through a function, there are two methods in C language: value transfer and address transfer, that is, pointer transfer, in C ++, we introduce reference transfer. Each of these three transfer methods has its own characteristics. Here we will focus on the characteristics of the reference transfer.
 1 #include<iostream> 2 using namespace std; 3 #include <Windows.h> 4 struct BigData 5 { 6       int array [1000]; 7 }; 8 void DealBigData1(BigData& x) 9 {10       x.array[0] = 0;11       x.array[1] = 1;12       x.array[2] = 2;13 }14 void DealBigData2 (BigData x)15 {16       x.array [0]= 0;17       x.array [1]= 1;18       x.array [2]= 2;19 }20 void TestReference()21 {22       BigData bd ;23       int begin = GetTickCount ();24       for (int i = 0; i < 1000000; ++i )25       {26             DealBigData1(bd);27       }28       int end = GetTickCount ();29       cout<<"cost time:" <<end - begin<<endl ;30       begin = GetTickCount ();31       for (int i = 0; i < 1000000; ++i )32       {33             DealBigData2(bd);34       }35       end = GetTickCount ();36       cout<<"cost time:" <<end - begin<<endl ;37 }38 int main()39 {40       TestReference();41       return 0;42 }

 

The running result of the above Code is: from the running result, it is not difficult to see that, compared with passing the value, transferring the reference will undoubtedly greatly improve the program performance. 2. When the reference is used as the return value of the Function 
 1 int& Add (int d1, int d2) 2 { 3 int ret = d1 + d2; 4 return ret ; 5 } 6 void test() 7 { 8 int a = 3, b = 4; 9 int c = Add( a, b );10 cout<<"c:" <<c<< endl;11 }

 

The above code is incorrect because the reference receives a local or temporary variable address and returns the following warning during compilation: this is because the function will create a temporary variable when it returns the result. When we reference this temporary variable as the return value of the function, we all know that temporary variables will be destroyed after the function is run. Such writing is undoubtedly incorrect and is not recommended. The following code uses passing values as the return value of the function. It is correct. When we want to use reference as the return value of the function, we should return a parameter passed by reference, that is correct.
 1 int Add1 (int a, int b) 2 { 3       int ret = a + b; 4       return ret; 5 } 6 int& Add2(int& a, int b) 7 { 8       int ret = a + b; 9       return ret;10 }11 void test1()12 {13       int ret = Add1(1, 2);14       cout<<"ret:" <<ret<< endl;15 }16 void test2()17 {18       int a = 3, b = 4;19       int c = Add2( a, b );20       cout<<"c:" <<c<< endl;21 }22 int main ()23 {24       test1();25       test2();26       return 0;27 }
Let's look at the differences between the two functions that use the passed value as the function return value and the passed reference as the function return value, for example:

 

It is not difficult to find that the ret value is put into the eax register when the value is returned, and the ret address is put into the eax register when the value is returned. Therefore, when using the reference as the return value of the function, we should note that:
1. Do not return the quote of a temporary variable. 2. If the returned object returns the current function, the operator field still exists, it is best to enable the operator to introduce the operator to return, because this is more efficient.
In C, there are pointers, while in C ++, so what is the difference and connection between pointers and references?
1. The pilot variable can only be initialized at the time of definition, and cannot be changed to other variables (from the end of the pilot variable). The value of the pointer variable is variable. 2. the quote must point to a valid variable. The pointer can be null. 3. The meaning of the sizeof pointer object and the cited object is not exactly the same. Sizeof gets the pointer of the variable pointed to, and the pointer of inclusizeof is the pointer of the object address. 4. pointer and ⽤ ⾃ (++) ⾃ (--) are meaningless. 5. the pointer to the ⽤ ⽐ pointer is safer than the ⽽ ⾔ pointer.
Therefore, when using pointers and references, we should know that although pointers are more flexible, they are more dangerous. Make sure to check whether the pointer is null when setting the cursor pointer. It is best to set the value 0 after the address indicated by the pointer is released, otherwise there may be a wild pointer problem.

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.