Summary of C + + references

Source: Internet
Author: User
Tags define function

One, a reference to a variable:

Reference: is an alias of a variable (the target), and the operation of 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: Char ch;

Char &rp=ch;

1) The reference is only the alias of the variable, not the actual definition of a variable, so the reference itself does not consume memory, but is in common with the target variable to point to the memory address of the target variable.

2) The fetch address character in the expression & is no longer the address of the variable, but is used to indicate that the variable is a reference type variable.

3) When a reference is defined, it must be initialized.

Example code:

#include <stdio.h> #include reference instance in <iostream>using namespace std;//c++ void fun (int &x) {     printf (" The value of the formal parameter is:%d\n ", x);     printf ("The address of the formal parameter is:%d\n", &x);     x+=10;} void fun2 (int *num) {  printf ("The value of the formal parameter is:%d\n", *num);  printf ("The address value of the formal parameter is:%d\n", num); 2686724  printf ("The address of the formal parameter is:%d\n", &num);  2686704 this and  *num = (*num) +10;} int main (void) {   int num = 4,a=3;    printf (the value of the "argument num is:%d\n", num);    printf ("The address of the actual parameter num is:%d\n", &num);//Both are the same fun    (num);   cout<< "num value is:" <<num<<endl; The value of num is changed to   fun2 (&a);   printf ("The value of argument A is:%d\n", a);   printf ("The address of argument A is:%d\n", &a);//   return 0;}

  

you can see 1. The address of the reference and the target variable is the same, and the modification to the reference is the modification of the target variable.

2. The next side uses the pointer as the function parameter, passes the address, the pointer variable address is 2686608, and its value is 2686696 (the value that exists in the pointer's address), 2686696 this address points to the value is 3, namely Num's value.

3. The pointer variable has its own value (2686608), and the address of Num (2686696) is not the same, and the referenced address is the same as the value of the variable.

II. Application of References

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.

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

(2) The use of pointers as parameters of the function can also 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 errors 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.

Just like the example above.

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.

#include <stdio.h> #include <iostream>using namespace std;void test_const (); int main (void) {   test_ const ();   return 0;} void Test_const () {   int a=1;     int &b=a;     b=2;    cout<< "a=" <<a<<endl;//2    int c=1;    const INT &d=c;   d=2;//Compilation Error error:assignment of READ_ONLY reference ' d '    c=2;//correct    cout<< "c=" <<c<< endl;//}

  

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.

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>using namespace std; Float temp;//defines the global variable temp float fn1 (float R);//Declare Function fn1 float &fn2 (float R);//Declare Function fn2 R float fn1 (float r) {//define function FN1, which returns The return value method returns the function value    temp= (float) (r*r*3.14);    return temp;  }  Float &fn2 (float r) {///define function FN2, which returns the function value     temp= (float) (r*r*3.14) as a reference;     return temp; } int main () {     float e=10.0;     Float A=FN1 (10.0);//1th case, the system generates a copy of the value to return (that is, the temporary variable)    //float &B=FN1 (10.0);//2nd case, there may be an error (different C + + systems have different provisions)/   * Error:invalid initialization of Non-const reference of type ' float& ' from an rvalue of type ' float '   *     ///cannot Returns a reference to a temporary variable or a local variable from the called function     float c=fn2 (10.0);//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     E=d;     cout<< "a=" <<a<< ", c=" <<c<< ", d=" <<d<< ", e=" <<e<<endl;     a=314,c=314,d=314     return 0;   }

  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. A compilation error occurs in the 2nd case in Example 5.

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

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;//Initializes a reference to the 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.

Citation summary

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

Very good writing: http://www.cnblogs.com/gw811/archive/2012/10/20/2732687.html

save, prevent forgetting

Summary of C + + references

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.