Reference one of the two articles C ++

Source: Internet
Author: User
Reference is a new language feature introduced by C ++. It is one of the important content commonly used in C ++. Correct and flexible use of reference can enable Program Concise and efficient. In my work, I found that many people only take it for granted. In some subtle occasions, it is easy to make mistakes. The reason is mostly because they have not figured out their origins. Therefore, I will discuss references in detail in this article, hoping to help you better understand and use references.

References

A reference is an alias of a variable (target). The referenced operation is exactly the same as the direct operation on a variable.

Declared method: type identifier & reference name = target variable name;

[Example 1]: int A; Int & RA = A; // defines reference Ra, which is a reference of variable A, that is, alias

Note:

(1) & this is not an address calculation, but an identifier.

(2) type identifier refers to the type of the target variable.

(3) When declaring a reference, it must be initialized at the same time.

(4) After the reference declaration is complete, it is equivalent that the target variable name has two names, namely, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names.

Ra = 1; equivalent to a = 1;

(5) declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, therefore, the reference itself does not occupy storage units, and the system does not allocate storage units to the reference. Therefore, finding the address for the reference is to find the address for the target variable. & RA and &.

(6) arrays cannot be referenced. An array is a collection composed of several elements, so an array alias cannot be created.

Reference Application

1. Reference as a parameter

An important role of reference is as a function parameter. In the previous C language, function parameter transfer was a value transfer. If a large piece of data is used as a parameter transfer, a pointer is often used, because this avoids the whole piece of data from being pushed to the stack, it can improve program efficiency. But now (in C ++), another option that is equally efficient (which is required in some special cases) is reference.

[Example 2 ]:

Void swap (Int & P1, Int & p2) // The parameter P1 and P2 of the function are referenced.
{Int P; P = p1; P1 = P2; P2 = P ;}

To call this function in a program, the call point of the corresponding main function can be directly called using the variable as the real parameter, without any special requirements on the real variable. For example, the swap function defined above can be written as follows:

Main ()
{
Int A, B;
Cin> A> B; // enter the values of A and B.
Swap (a, B); // directly call the swap function using variables A and B as real parameters.
Cout <A <<'' <B; // output result
}

When the above program is running, if the input data is 10 20 and then press enter, the output result is 20 10.

As shown in [Example 2:

(1) passing a reference to a function has the same effect as passing a pointer. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.

(2) using the reference parameter to pass the function does not generate a copy of the real parameter in the memory, it is directly to operate on the real parameter; while using the general variable to pass the function parameter, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. if the object is passed, the copy constructor will also be called. Therefore, when the data transmitted by a parameter is large, it is better to use reference than to transmit a parameter using a common variable.

(3) Although using pointers as function parameters can achieve the same effect as using references, in the called function, storage units must be allocated to the parameters, the "* pointer variable name" format must be used repeatedly for calculation, which can easily lead to errors and the program reading is poor. On the other hand, at the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

If you want to use references to improve program efficiency and protect the data transmitted to the function from being changed in the function, you should use regular references.

2. Frequent reference

Common Reference declaration method: const type identifier & reference name = target variable name;

The reference declared in this way cannot be modified by reference to the value of the target variable, so that the referenced target becomes const, achieving the security of reference.

[Example 3 ]:

Int;
Const Int & RA =;
Ra = 1; // Error
A = 1; // correct

This is not just to makeCodeIt is more robust and has some other needs.

[Example 4]: assume that the following function declaration is available:

String Foo ();
Void bar (string & S );

The following expression is invalid:

Bar (FOO ());
Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.

The referenced parameter should be defined as const if it can be defined as Const.

Reference is a new language feature introduced by C ++. It is one of the important content commonly used in C ++. Correct and flexible use of reference can make the program concise and efficient. In my work, I found that many people only take it for granted. In some subtle occasions, it is easy to make mistakes. The reason is mostly because they have not figured out their origins. Therefore, I will discuss references in detail in this article, hoping to help you better understand and use references.

References

A reference is an alias of a variable (target). The referenced operation is exactly the same as the direct operation on a variable.

Declared method: type identifier & reference name = target variable name;

[Example 1]: int A; Int & RA = A; // defines reference Ra, which is a reference of variable A, that is, alias

Note:

(1) & this is not an address calculation, but an identifier.

(2) type identifier refers to the type of the target variable.

(3) When declaring a reference, it must be initialized at the same time.

(4) After the reference declaration is complete, it is equivalent that the target variable name has two names, namely, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names.

Ra = 1; equivalent to a = 1;

(5) declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, therefore, the reference itself does not occupy storage units, and the system does not allocate storage units to the reference. Therefore, finding the address for the reference is to find the address for the target variable. & RA and &.

(6) arrays cannot be referenced. An array is a collection composed of several elements, so an array alias cannot be created.

Reference Application

1. Reference as a parameter

An important role of reference is as a function parameter. In the previous C language, function parameter transfer was a value transfer. If a large piece of data is used as a parameter transfer, a pointer is often used, because this avoids the whole piece of data from being pushed to the stack, it can improve program efficiency. But now (in C ++), another option that is equally efficient (which is required in some special cases) is reference.

[Example 2 ]:

Void swap (Int & P1, Int & p2) // The parameter P1 and P2 of the function are referenced.
{Int P; P = p1; P1 = P2; P2 = P ;}

To call this function in a program, the call point of the corresponding main function can be directly called using the variable as the real parameter, without any special requirements on the real variable. For example, the swap function defined above can be written as follows:

Main ()
{
Int A, B;
Cin> A> B; // enter the values of A and B.
Swap (a, B); // directly call the swap function using variables A and B as real parameters.
Cout <A <<'' <B; // output result
}

When the above program is running, if the input data is 10 20 and then press enter, the output result is 20 10.

As shown in [Example 2:

(1) passing a reference to a function has the same effect as passing a pointer. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.

(2) using the reference parameter to pass the function does not generate a copy of the real parameter in the memory, it is directly to operate on the real parameter; while using the general variable to pass the function parameter, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. if the object is passed, the copy constructor will also be called. Therefore, when the data transmitted by a parameter is large, it is better to use reference than to transmit a parameter using a common variable.

(3) Although using pointers as function parameters can achieve the same effect as using references, in the called function, storage units must be allocated to the parameters, the "* pointer variable name" format must be used repeatedly for calculation, which can easily lead to errors and the program reading is poor. On the other hand, at the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

If you want to use references to improve program efficiency and protect the data transmitted to the function from being changed in the function, you should use regular references.

2. Frequent reference

Common Reference declaration method: const type identifier & reference name = target variable name;

The reference declared in this way cannot be modified by reference to the value of the target variable, so that the referenced target becomes const, achieving the security of reference.

[Example 3 ]:

Int;
Const Int & RA =;
Ra = 1; // Error
A = 1; // correct

This is not just to make the code more robust, but also some other needs.

[Example 4]: assume that the following function declaration is available:

String Foo ();
Void bar (string & S );

The following expression is invalid:

Bar (FOO ());
Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.

The referenced parameter should be defined as const if it can be defined as Const.

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.