Usage and application examples of references (&) in C + +

Source: Internet
Author: User
Tags function definition

For those of you who are accustomed to using C for development, you may be confused when you see the & symbols appearing in C + +, because in c the symbol represents the fetch address character , which is often used to assign values to pointers in function arguments . But in C + + it has a different purpose, mastering C + + & symbols is a good way to improve the efficiency of code execution and enhance the quality of code.

Reference is a new language feature introduced by C + +, which is one of the most important contents in C + +, and the correct and flexible use of reference can make the program concise 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.

I. Introduction of Citation

A reference is an alias for a variable (the target), and the action on the reference is exactly the same as the direct operation on the variable.

Declarative method of Reference: type identifier & reference name = target variable name;

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

Description

(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.

Second, reference Application

  1. Reference as parameter

An important function of a reference is as a function parameter. In the previous C language, function parameter passing is a value pass, if there are large chunks of data passed as parameters, the scheme used is often pointers, because this can avoid the whole piece of data stack, can improve the efficiency of the program. But now (c + +) has added an equally efficient choice (which in some special cases is a necessary choice), which is a reference.

"Example 2":

void swap (intint// parameter P1 of the function here, p2 are all reference int p; p=p1; p1=p2; p2=p;}

To call this function in a program, the call point of the corresponding keynote function is called directly with the variable as an argument, without any special requirement of the real parametric. For example: corresponding to the SWAP function defined above, the corresponding keynote function can be written as:

Main () {  int A A, cin// input A/b two variable value // call the swap function directly with variables A and B. as arguments  "// output result }

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

By "Example 2" can be seen:

(1) The effect of passing a reference to a function is the same as passing a pointer. At this point, the parameter of the function is used as the real parametric or an alias of the object in the original central melody function, so the operation of the parameter variable in the function is the operation of its corresponding target object (in the central Melody function).

(2) using the parameters of the reference transfer function, in memory does not produce a copy of the argument, it is directly to the actual parameter operation, while using the general variable transfer function parameters, when a function call, you need to assign a storage unit to the parameter, the parameter variable is the copy of the argument variable; Therefore, when the parameter passes the data is large, uses the reference to pass the parameter with the general variable efficiency and occupies the space to be good.

(3) The use of pointers as parameters of the function, although also can achieve with the use of reference, but in the function of the parameter allocation of the same storage unit, and the need to re-use "* pointer variable name" in the form of operations, which is prone to error and poor program reading; On the other hand, at the call point of the keynote function You must use the address of the variable as the argument. And references are easier to use and clearer.

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

  2. Frequently quoted

Common 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, thus making the target of the reference a const, which achieves the security of the reference.

"Example 3":

int A; Const int &ra=A;ra=1// error a=1// correct

This is not just about making the code more robust, but there are other areas of need.

Example 4: Suppose you have the following function declaration:

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

Then the following expression will be illegal:

Bar (foo ()); Bar ("helloWorld");

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

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


  3. Reference as return value

To return a function value as a reference, the function definition is formatted as follows:

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

Description

(1) Return function value by reference, need to add & in front of function name when defining function

(2) The greatest benefit 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 (which returns the function value using the return value method), and a function fn2 that returns the value of the function in the referenced method.

#include <iostream.h>floatTemp//Define Global Variables TempfloatFN1 (floatR);//declaring a function fn1float&AMP;FN2 (floatR);//declaring a function fn2floatFN1 (floatR//defines the function fn1, which returns the function value as a method of returning a value{Temp=(float) (r*r*3.14); returntemp;}float&AMP;FN2 (floatR//defines the function fn2, which returns the function value as a reference{Temp=(float) (r*r*3.14); returntemp;}voidMain ()//Main function{floatA=FN1 (10.0);//In the 1th case, the system generates a copy of the value to return (that is, the temporary variable)   float&AMP;B=FN1 (10.0);//2nd case, error may occur (different C + + systems have different rules)//You cannot return a temporary variable or a reference to a local variable from a function that is being tuned   floatC=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 a function that is being tuned   float&AMP;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 a function that is being tunedcout<<a<<c<<D;}

Reference as the return value, the following rules must be observed:

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

(2) You cannot return a reference to the memory that is allocated inside the function. This article can refer to effective c++[1] Item 31. Although there is no passive destruction of local variables, there are other embarrassing situations in which the case (a reference to new allocation of memory within the function) is returned. For example, a reference returned by a function is only present as a temporary variable, not given an actual variable, and the space pointed to by the reference (allocated by new) cannot be freed, resulting in memory leak.

(3) A reference to a class member can be returned, but preferably a const. This principle can be referenced by effective C++[1] Item 30. The main reason is that when an object's property is associated with a business rule, its assignment is often related to the state of some other attribute or object, so it is necessary to encapsulate the assignment in a business rule. If other objects can get a very good reference (or pointer) to the property, the simple assignment of that property will break the integrity of the business rules.

(4) Overloading of references and some operators:

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; Therefore, the return value of these two operators should be a stream reference that still supports both operators. Alternative options include returning a stream object and returning a pointer to a stream object. But for a stream object to be returned, the program must recreate (copy) a new stream object, that is to say, two consecutive << operators are actually for different objects! It's not acceptable to anyone. The << operator cannot be used consecutively for returning a stream pointer. Therefore, returning a Stream object reference is the only option. This unique choice is key, it shows the importance of the reference and the irreplaceable, perhaps this is the introduction of the concept of reference in the C + + language is the reason for it. Assignment operator =. This operation, like the Fuchang operator, can be used consecutively, for example: x = j = 10, or (x=10) = 100; The return value of the assignment operator must be an lvalue so that it can be assigned again. The reference is therefore the only return value selection for this operator.

The "Example 6" test uses the value of the function that returns the reference as the lvalue of the assignment expression.

#include <iostream.h>int&put (intn);intvals[Ten];interror=-1;voidMain () {put (0)=Ten;//The value of the put (0) function as the left value is equivalent to vals[0]=10;Put9)= -;//The value of the put (9) function as the left value is equivalent to vals[9]=20;cout<<vals[0];cout<<vals[9];}int&put (intN) {if(n>=0&& n<=9)returnVals[n];Else{cout<<"Subscript Error";returnerror;}}

(5) In some other operators, it is not possible to return a reference: +-*/arithmetic character. They cannot return references, effective c++[1] Item23 detailed discussion of this issue. 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 allocated object, and returning a static object reference. According to the preceding reference as the three rules for the return value, the 2nd and 32 scenarios are deprecated. A reference to a static object also causes an error because ((a+b) = = (C+d) is always true. So the only option left is to return an object.

  4. References and polymorphism

A reference is another means of producing a polymorphic effect, in addition to pointers. This means that a reference to a base class can point to its derived class instance.

"Example 7":

class A;  class B: public a{...}; b b; A  //  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, which 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 citations

(1) In the use of reference, it is meaningless to simply give a certain variable name, the purpose of the reference is mainly used in the transfer of function parameters, to solve the problem of the transfer efficiency and the space of large data or objects.

(2) using the parameters of the reference transfer function, it can ensure that the parameters are not generated in the transfer of the copy, improve the efficiency of the transfer, and through the use of const, to ensure the security of reference delivery.

(3) The difference between a reference and a pointer is that the pointer is indirectly manipulated by the variable it points to after it points to an object through a pointer variable. The use of pointers in the program, the readability of the program, 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. Reference is recommended for the stream operator << and >>, the return value of the assignment operator =, the parameter of the copy constructor, the parameter of the assignment operator =, and other cases.

Refer to the original Portal: please click

Usage and application examples of references (&) in C + +

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.