C + + Learning 4-References

Source: Internet
Author: User

C + + references (Reference)

Reference (Reference) is another extension of C + + language relative to C, and is one of the most important content in C + +. Similar to a pointer, just substituting "*" with "&" when declaring. The correct and flexible use of references can make the program simple and efficient. I found in my work that many people use it just for a reason, and in some subtle situations, it's easy to make mistakes, mostly because they don't know the origin. Therefore, in this article I will be a detailed discussion of the reference, I hope that you better understand and use of reference to play a role.

Reference
A reference is an alias, which must be initialized when declared, and used primarily as a function's formal parameter in the actual code.

(1) & Here is not the address calculation, but the role of identification.
(2) The type identifier refers to the type of the target variable.
(3) When declaring a reference, it must be initialized at the same time.
(4) When the declaration is complete, the target variable name is equivalent to two names, that is, the target name and reference name, and the reference name cannot be used as an alias for the other variable names.
Ra=1; equivalent to A=1;
(5) Declare a reference, not a new variable, it only means that the reference name is an alias of the target variable name, it is not a data type in itself, so the reference itself does not account for the storage unit, and the system does not assign a storage unit to the reference. Therefore, the reference to the address, that is, the target variable to find the address. &ra is equal to &a.
(6) You cannot create a reference to an array. Because an array is a collection of several elements, you cannot create an alias for an array.

Ii. reference Applications (see C + + reference topics)
1. References as parameters
2. Frequently cited
3. Reference as return value
4. References and polymorphism

A reference can be considered an alias of the referenced object, and it must be initialized at the same time when the reference is declared. The declarative methods for referencing are as follows:
Type identifier & Reference name = referenced object

Examples of C + + references:

int a = 10;
int &b = A;
cout << a << "" << b << Endl;
cout << &a << "<< &b << Endl;

In this case, variable B is the reference to variable A, and the program runs as follows:
10
0x64fe68 0x64fe68

From this program we can see that both the variable A and the variable B are pointing to the same address, that is, the variable B is another name for variable A, or it can be understood that 0x64fe68 has two names: A and B. Since both the reference and the original variable point to the same address, the value of the variable stored in the original variable can also be modified by reference, as shown in Example 2, and the result of the final program running is output two 20, which shows that the value of the original variable A has been modified by the reference variable B.
[Example 2] Modify the value in the original variable by reference:
int a = 10;
int &b = A;
b = 20;
cout << a << "" << b << Endl;


If we do not want to change the value of the original variable by reference, we can declare the reference as follows:
Const type identifier & reference name = referenced variable name

This type of citation becomes a constant reference. As shown in Example 3, we declare that B is a constant reference, and then try to modify the value of the A variable by B, resulting in a compile error. Although the constant reference cannot modify the value of the original variable, we can still modify the original variable value through the original variable itself, as in Example 3, we use A=20; The statement changes the value of a variable from 10 to 20, which is not a grammatical problem.

[Example 3] The original value cannot be modified by a common reference:
Copy formatted new window

int a = 10;
const int &b = A;
b = 20; Compile error
A = 20;

By Example 2, we can know that by referencing we can modify the value of the original variable, which makes it useful for function passing arguments or function return values.

1) function Reference parameter
If we specify a function's formal parameter as a reference when declaring or defining a function, the argument is passed directly to the parameter when the function is called, instead of passing the copy of the argument to the parameter. As a result, if the parameter is modified in the body of the function, the value of the argument is also modified. This is different from the normal invocation of a function.


Parameter passing of C-language function
Pass-by-value, pass-by-value if a large data item is passed, the assignment data results in a longer execution time

C++
Pass-by-reference to avoid the overhead of copying large amounts of data to improve performance

The difference between a reference and a pointer
The pointer is a variable that can be assigned to an address that points elsewhere
The reference must be initialized and never be associated with a different variable
Because the pointer is also a variable, you can have a reference to a pointer variable

int *a = nullptr;
int * &ptr = A; Represents the int* reference ptr initialized to a
int B = 8;
PTR = &b; OK, PTR is an alias of a, is a pointer

void &a = 3; ---------Note that this is not legal.
Void is syntactically equivalent to a type, essentially not a type, but does not have any variable or object whose type is void

Cannot traverse the referenced array
int a[10] = {0};
int &ra[10] = A; Error cannot create an array of reference types

No references to pointers and references
int A;
int &ra = A;
int & *ptr = &ra; Error attempting to define a reference pointer

A null pointer does not have a null reference, and each reference is valid

Parameter passing by reference
Passing a reference to a function is as effective as passing a pointer
Using references as arguments is more clear syntax than using pointers

void swap (int &x, int &y); Reference as parameter

void swap (int &x, int &y)//function implementation almost the same as the original
{
int temp = x;
x = y;
y = temp;
}

void swap (int *x, int *y)
{
int z = *x;
*x = *y;
*y = Z;
}

==============================================================
#include <iostream>
using namespace Std;

void foo (int val)
{
val = 10;
}

void bar (int &val)
{
val = 10;
}

void Zoo (int *pval)
{
*pval = 10;
}

int main ()
{
int a = 1;
int b = 1;
int c = 1;
Foo (a);
Bar (b);
Zoo (&AMP;C);
cout << a << "<< b <<" "<< c << Endl;

return 0;
}

====================================================================

Parameter passing by reference
Use references as arguments and return values to the meaning of the function
A function can return only one value. What to do if a program needs to return two values from a function
One way to solve this problem is to pass two parameters to the function and then fill in the correct values by the function toward the target.

When a function returns a value, a copy of the value is generated. Instead of generating a copy of the value when referencing the return value, it improves efficiency.

int result = 0;
int &func (int r)//return reference
{
result = R * r;
return result;
}

Note: If you return a reference to a variable or object that is not in scope, there is a problem.
This is as serious as returning a local-scope pointer.

int &func (int r)
{
int result = 0;
result = R * r;
return result; Returns a reference to a local variable
}

int main ()
{
int &val = func (5); The reference returned by the error is a local variable
return 0;
}

=========================================================================

In addition, we need to pay attention to a small problem. If we use the Valplus function in example 5 to define the form shown in precedent 6, then this program will have a problem, the scope of the variable B is only within the body of the Valplus function, when the function call is complete, the B variable will be destroyed. At this point, if we return the value of the B variable to the variable num2 by reference, it is possible that the B variable has been destroyed before the copy, resulting in the num2 variable getting no return value. Although this situation does not occur in some compilers, we should try to avoid this when designing the program.

In Example 4 and example 5, we are using reference passing parameters to avoid this point. The normal return value does not exist because the compiler copies the return value to the temporary storage space before destroying the B variable.


[Example 6] An example that might not get the return value://Because B is a local variable and is automatically destroyed (stack) when the program finishes

int & Valplus (int a)
{
int B = A + 5;
return b;
}

C + + Learning 4-References

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.