Usage and application of reference (&) in C + + _c language

Source: Internet
Author: User
Tags define function function definition

For those friends who are used to developing C, it may be confusing to see the & symbol appearing in C + +, because this symbol in C language takes the address character, but it has different uses in C + +, mastering the & symbol of C + +, is a good way to improve the efficiency of code execution and enhance code quality.

Reference is a new language feature introduced by C + +, which is one of the most important contents in C + +, and using references correctly and flexibly can make the program concise and efficient. I found in my work that many people use it just for granted, in some delicate occasions, it is easy to make mistakes, the original, mostly because there is no clear source. So in this article I will discuss the reference in detail, hoping to better understand and use references to play a role.

Introduction of references

A reference is an alias to a variable (the target), and the operation of the reference is exactly the same as the direct manipulation of the variable.

Referenced declaration method: type identifier & reference name = target variable name;

"Example 1":
int A; int &ra=a; Defines a reference to RA, which is a reference to variable A, that is, an alias

Description

(1) & This is not to seek the address operation, but to play 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) After the declaration of the reference, the equivalent of the target variable name has two names, that is, the target's original name and reference name, and can no longer be used as an alias for other variable names.

Ra=1; equivalent to A=1;

(5) Declaring a reference, not a new definition of a variable, it only means that the reference name is an alias of the target variable name, it is not a data type itself, so the reference itself does not occupy the storage unit, and the system does not allocate the storage unit to the reference. Therefore: the reference to the address, that is, the target variable to find the address. &ra and &a are equal.

(6) Cannot establish a reference to an array. Because an array is a collection of several elements, you cannot create an alias for an array.

Second, the application of reference

1, reference as a parameter

An important function of a reference is as an argument to a function. The previous C language function parameter transfer is value transfer, if there are large chunks of data as a parameter transmission, the use of the scheme is often pointers, because this can avoid the whole block of data stack, can improve the efficiency of the program. But now (c + +) has added an equally efficient choice (and, in some special cases, a necessary choice), is a reference.

"Example 2":

Copy Code code as follows:

void swap (int &p1, int &p2)//The formal parameter P1 of the function, p2 are all references
{int p; p=p1; p1=p2; p2=p;}

In order to call the function in the program, the call point of the corresponding calling function is invoked directly with the variable as the argument, without the need for the real parametric to have any special requirements. For example, corresponding to the SWAP function defined above, the corresponding keynote function can be written as:
Copy Code code as follows:

Main ()
{
int a,b;
cin>>a>>b; Enter the value of the A,B two variable
Swap (A,B); Call the swap function directly with variables A and B as arguments
cout<<a<< ' ' <<b; Output results
}

When the above program runs, the output is 20 10 if you enter data 10 20 and return.

As can be seen from "Example 2":

(1) The effect of passing a reference to a function is the same as passing a pointer. At this time, the parameter of the function is called the real parametric or an alias of the object in the original keynote function, so the operation of the parameter variable in the modulated function is the operation of its corresponding target object (in the keynote function).

(2) using the parameter of the reference pass function, there is no copy of the argument in memory, it is a direct operation of the argument, while using a generic variable to pass the function's arguments, when a function call is made, the parameter is required to allocate the storage unit, the parameter variable is a copy of the argument variable, and the copy constructor is called if the object is passed. Therefore, when the parameter passes the data is big, uses the reference to pass the parameter with the general variable the efficiency and occupies the space to be good.

(3) The use of pointers as a function of the parameters, although also can achieve the effect of using references, however, it is very easy to make errors and poor reading of the program in the same way that the parameters are allocated to the parameters, and the "* pointer variable name" needs to be used repeatedly. On the other hand, at the call point of the calling function, You must use the address of the variable as an argument. And references are easier to use and clearer.

If you want to use the reference to improve the efficiency of the program, but also protect the data passed to the function is not changed in the function, you should use the constant reference.

2, often cited

Constant reference declaration method: Const type identifier & reference name = target variable name;

A reference declared in this way cannot be modified by reference to the value of the target variable, so that the target of the reference becomes const, and the reference security is reached.

"Example 3":

Copy Code code as follows:

int A;
const INT &ra=a;
Ra=1; Error
A=1; That's right

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

"Example 4": Suppose you have the following function declaration:

Copy Code code as follows:

string foo ();
void Bar (string & S);

Then the following expression will be illegal:

Bar (foo ());
Bar ("Hello World");

The reason is that Foo () and the "Hello World" string all produce a temporary object, whereas in C + + These temporary objects are const types. So the expression above is an illegal attempt to convert a const-type object to a non-const type.

Reference parameters should be defined as const if they can be defined as const.


3. Reference as return value

To return a function value as a reference, the function definition should be in the following format:

Type identifier & function name (parameter list and type description)
{function Body}

Description

(1) To return function values by reference, the function needs to be defined before the function name is added &

(2) The best advantage of returning a function value with a reference is that it does not produce a copy of the returned value in memory.

Example 5 The following program defines a normal function fn1 (it returns the function value using the return value method), and another function fn2, which returns the function value in the referenced method.

Copy Code code as follows:

#include <iostream.h>
float temp; Defining Global Variables Temp
Float fn1 (float R); declaring functions Fn1
Float &fn2 (float R); declaring functions Fn2
Float fn1 (float r)//definition function FN1, which returns the function value as a return value method
{
temp= (float) (r*r*3.14);
return temp;
}
Float &fn2 (float R)//define function FN2, it returns function value by reference
{
temp= (float) (r*r*3.14);
return temp;
}
void main ()//main function
{
Float A=FN1 (10.0); In the 1th case, the system generates a copy of the value to return (that is, a temporary variable)
Float &B=FN1 (10.0); 2nd, there may be an error (different C + + systems have different rules)
Cannot return a reference to a temporary variable or a local variable from a called function
Float C=FN2 (10.0); In the 3rd case, the system does not generate a copy of the return value
You can return a reference to a global variable from the called function
Float &D=FN2 (10.0); In the 4th case, the system does not generate a copy of the return value
You can return a reference to a global variable from the called function
cout<<a<<c<<d;
}

reference as the return value, you must observe the following rules:

(1) A reference to a local variable cannot be returned. This can refer to item 31 of effective c++[1]. The main reason is that local variables are destroyed after the function returns, so the returned reference becomes a reference to "no references" and the program goes into an unknown state.

(2) cannot return a reference to the memory allocated by the function's internal new. This can refer to item 31 of effective c++[1]. Although there is no problem of passive destruction of local variables, it can be faced with other embarrassing situations in this case (returning the reference of allocating memory within new function). For example, a reference returned by a function only appears as a temporary variable without being given an actual variable, so the space that the reference points to (allocated by new) cannot be released, causing memory leak.

(3) You can return a reference to a class member, but preferably a const. This principle can refer to item 30 of effective c++[1]. The main reason is that when an object's properties are associated with a certain business rule (business rules), the assignment is often related to the state of some other property or object, so it is necessary to encapsulate the assignment operation in one business rule. If other objects can get a very strong reference (or pointer) to the property, then a simple assignment to that property can break the integrity of the business rule.

(4) referencing the overloads of some operators:

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; So the return value of these two operators should be a stream reference that still supports both operators. Alternative alternatives include: returning a Stream object and returning a stream object pointer. But for returning a stream object, the program must reconstruct (copy) a new stream object, that is to say, the continuous two << operators are actually targeted at different objects! It's not acceptable. The << operator cannot be used continuously for returning a stream pointer. Therefore, returning a Stream object reference is the only choice. The only option is critical, which illustrates the importance and irreplaceable nature of references, and perhaps that's why the concept of referencing is introduced in the C + + language. Assignment operator =. This operation, like the Fuchang operator, can be used continuously, for example: x = j = 10; or (x=10) = 100; The return value of the assignment operator must be a left value so that it can be continued to be assigned. So the reference is the only return value selection for this operator.

The example 6 test uses a function value that returns a reference as the left value of the assignment expression.

Copy Code code as follows:

#include <iostream.h>
int &put (int n);
int vals[10];
int error=-1;
void Main ()
{
Put (0) = 10; The put (0) function value as the left value is equivalent to vals[0]=10;
Put (9) = 20; The put (9) function value as the left value is equivalent to vals[9]=20;
cout<<vals[0];
cout<<vals[9];
}
int &put (int n)
{
if (n>=0 && n<=9) return vals[n];
else {cout<< "subscript error"; return error;}
}

(5) In some other operators, but must not return the reference: +-*/arithmetic character. They cannot return the reference, effective c++[1] 's ITEM23 discusses the issue in detail. The main reason is that these four operators do not have side effect, so they must construct an object as the return value, and the optional scheme includes: Returning an object, returning a reference to a local variable, returning a reference to a new assigned object, and returning a static object reference. The 2nd and 32 scenarios have been deprecated, based on the three rules referred to above as the return value. A reference to a static object also causes an error because ((a+b) = = (C+d)) will always be true. So the only option left is to return one object.

4, references and polymorphism

A reference is another means of producing a polymorphic effect, other than a pointer. This means that a reference to a base class can point to its derived class instance.

"Example 7":

Copy Code code as follows:

Class A;
Class B:public a{...};
b b;
A &ref = b; Initializes a reference to a base class object with a derived class object

Ref can only be used to access the members inherited from the base class in the derived class object, and is the base class reference to the derived class. If a virtual function is defined in Class A and the virtual function is overridden in class B, a polymorphic effect can be generated by ref.

Iii. Summary of References

(1) In the use of references, it is meaningless to take individual names for a variable, and the purpose of reference is mainly to solve the problem of transferring efficiency and space of large chunks of data or objects in the transfer of function parameters.

(2) using the parameters of the reference transfer function, it can ensure that the parameter transfer does not produce a copy, improve the efficiency of transmission, and through the use of const, guarantee the security of reference transmission.

(3) The difference between a reference and a pointer is that the pointer indirectly operates on the variable it points to after it points to an object through a pointer variable. The use of pointers in programs, the readability of the program is poor, and the reference itself is the alias of the target variable, the operation of the reference is the operation of the target variable.

(4) The timing of the use of references. References are recommended for flow operators << and >>, the return value of the assignment operator =, the parameters of the copy constructor, the parameters of the assignment operator =, and others.

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.