Find a good article about quoting from somewhere else http://www.cnblogs.com/Mr-xu/archive/2012/08/07/2626973.html
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 this symbol represents the address-taking character, 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. In C + + learning to improve (3)---implicit pointer in the article, I introduced in detail the use of implicit pointer &, in fact, these two concepts are unified.
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 (int &p1, int &p2)//parameter p1 of the function here, p2 are references
{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, B;
cin>>a>>b; Enter the value of 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, 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; That's right
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 ("Hello World");
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>
float temp; Define Global Variables Temp
Float fn1 (float R); Declaring a function fn1
Float &fn2 (float R); Declaring a function fn2
Float fn1 (float R)//define function FN1, which returns the function value as a method of returning a value
{
temp= (float) (r*r*3.14);
return temp;
}
Float &fn2 (float R)//define function FN2, which returns the function value as a 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, the temporary variable)
Float &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
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 a function that is being tuned
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 a function that is being tuned
cout<<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 (int n);
int vals[10];
int error=-1;
void Main ()
{
Put (0) = 10; The value of the put (0) function as the left value is equivalent to vals[0]=10;
Put (9) = 20; 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 (int n)
{
if (n>=0 && n<=9) return vals[n];
else {cout<< "subscript error"; return error;}
}
(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 &ref = b; To initialize 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.
C + + Reference