References in C ++

Source: Internet
Author: User

C ++InReferenceIs an alias of a variable target. The referenced operation is exactly the same as the direct operation on the variable. Declared method: type identifier & reference name = target variable name;

Example 1 ]:

 
 
  1. Int a; int & ra = a; // definition 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: the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names.

 
 
  1. Ra = 1;
  2. Equivalent
  3. A = 1;

5) declare a reference. Instead of defining 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) You cannot create an array reference. 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 ++) it is necessary to add an equally efficient choice in some special cases), that is, reference.

Example 2 ]:

 
 
  1. Void swap (int & p1, int & p2) // The parameter p1 and p2 of the function are referenced.
  2. {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:

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

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

From example 2, we can see that:

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) When using the reference parameter to pass the function, there is no copy of the real parameter in the memory, and it directly operates 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, you must allocate storage units to the parameters in the called functions, 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 ]:

 
 
  1. Int;
  2. Const int & ra =;
  3. Ra = 1; // Error
  4. A = 1; // correct

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

Example 4: function declaration is as follows:

 
 
  1. string foo( );  
  2. void bar(string & s); 

The following expression is invalid:

 
 
  1. bar(foo( ));  
  2. 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.

3. Reference as return value

To return a function value by reference, the function must be defined in the following format:

Type identifier & function name parameter list and type description)
{Function body}

Note:

1) to reference the returned function value. When defining a function, add &

2) The biggest benefit of returning a function value with a reference is that a copy of the returned value is not generated in the memory.

Example 5: The following program defines a common function fn1, which returns the function value using the return value method). Another function fn2 returns the function value using a reference method.

 
 
  1. # Include <iostream. h>
  2. Float temp; // defines the global variable temp.
  3. Float fn1 (float r); // declare the function fn1
  4. Float & fn2 (float r); // declare the function fn2
  5. Float fn1 (float r) // defines the function fn1, which returns the function value in the return value method.
  6. {
  7. Temp = (float) (r * 3.14 );
  8. Return temp;
  9. }
  10. Float & fn2 (float r) // defines the function fn2, which returns the function value in reference mode.
  11. {
  12. Temp = (float) (r * 3.14 );
  13. Return temp;
  14. }
  15. Void main () // main Function
  16. {
  17. Float a = fn1 (10.0); // in 1st cases, the system generates a copy of the temporary variable to be returned)
  18. Float & B = fn1 (10.0); // in 2nd cases, different C ++ systems may have different rules)
  19. // A reference to a temporary or local variable cannot be returned from the called Function
  20. Float c = fn2 (10.0); // in 3rd cases, the system does not generate a copy of the returned value
  21. // A reference to a global variable can be returned from the called function.
  22. Float & d = fn2 (10.0); // in 4th cases, the system does not generate a copy of the returned value
  23. // A reference to a global variable can be returned from the called function.
  24. Cout <a <c <d;
  25. }

The reference must follow the following rules as the return value:

1) The local variable reference cannot be returned. For details, refer to Item 31 of Objective C ++ [1. The main reason is that local variables will be destroyed after the function returns, so the returned reference becomes a reference of "no finger", and the program enters the unknown state.

2) You cannot return a reference to the memory allocated by the new function. For details, refer to Item 31 of Objective C ++ [1. Although there is no Passive Destruction problem of local variables, it can return the reference of memory allocated by the new function in this case. For example, if a reference returned by a function only appears as a temporary variable and is not assigned with an actual variable, the space pointed to by this reference is allocated by new, cause memory leak.

3) You can return a reference to a class member, but it is best to use const. This principle can be referred to Item 30 of Objective C ++ [1. The main reason is that when an object attribute is associated with a business rule, its value assignment is often related to some other attributes or the state of the object, therefore, it is necessary to encapsulate the value assignment operation in a business rule. If other objects can obtain a non-constant reference or pointer of this attribute), a simple value assignment to this attribute will damage the integrity of business rules.

4) References and some Operator Overloading:

Stream operators <and>, which are often used consecutively, for example, cout <"hello" <endl; therefore, the return value of these two operators should be a stream reference that still supports these two operators. Other optional solutions include returning a stream object and returning a stream object pointer. But for a returned Stream object, the program must copy it again) to construct a new stream object. That is to say, two consecutive <operators are actually for different objects! This is unacceptable. If a stream pointer is returned, the <operator cannot be used consecutively. Therefore, returning a stream object reference is the only choice. This unique choice is critical. It illustrates the importance of reference and is irreplaceable. Maybe this is why the concept is introduced in C ++. Value assignment operator =. This operator can be used continuously like a stream operator, for example, x = j = 10; or (x = 10) = 100; the return value of the value assignment operator must be a left value, so that the value can be assigned. Therefore, it is referenced as the only return value choice of this operator.

Example 6: return the referenced function value as the left value of the value assignment expression.

 
 
  1. # Include <iostream. h>
  2. Int & put (int n );
  3. Int vals [10];
  4. Int error =-1;
  5. Void main ()
  6. {
  7. Put (0) = 10; // use the put (0) function value as the left value, equivalent to vals [0] = 10;
  8. Put (9) = 20; // use the put (9) function value as the left value, which is equivalent to vals [9] = 10;
  9. Cout <vals [0];
  10. Cout <vals [9];
  11. }
  12. Int & put (int n)
  13. {
  14. If (n> = 0 & n <= 9) return vals [n];
  15. Else {cout <"subscript error"; return error ;}
  16. }

5) among other operators, the reference: +-*/four Arithmetic Operators cannot be returned. They cannot return references. The Objective C ++ [1] Item23 discusses this issue in detail. The main reason is that these four operators do not have side effect. Therefore, they must construct an object as the return value. Optional solutions include: returning an object and returning a reference to a local variable, returns the reference of a newly assigned object and a static object reference. According to the preceding three rules that reference the returned value, both the 2nd and 3 schemes are rejected. Static object reference is caused by errors because (a + B) = (c + d) is always true. Therefore, only one object is returned.

4. References and Polymorphism

References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance.

Example 7 ]:

 
 
  1. Class;
  2. Class B: public {......};
  3. B B;
  4. A & Ref = B; // use A derived class object to initialize A reference to A base class Object

Ref can only be used to access the members inherited from the base class in a derived class object. It is a base class reference pointing to a derived class. If A virtual function is defined in Class A, and this virtual function is rewritten in Class B, A multi-state effect can be generated through Ref.

Reference Summary

1) In reference use, it is meaningless to simply give an alias to a variable. The purpose of reference is mainly used in function parameter transfer, solve the problem of poor transmission efficiency and space of large data or objects.

2) passing function parameters by reference can ensure that no copies are generated during parameter transfer and improve the transfer efficiency. Using const ensures the security of reference transmission.

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

4) when to use the reference. Stream operators <and>, return values of the value assignment operator =, parameters of the copy constructor, parameters of the value assignment operator =, and references are recommended in other cases.

I hope that the above content will help you.

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.