[Reserved] In-depth discussion of references in C ++

xiaoxiao2021-03-06  43

Abstract: Introducing the basic concepts of C references, through detailed application analysis and description, the reference is fully, thoroughly explained. Keywords: reference, const, polymorphism, pointer reference is a new language characteristic introduced by C , one of the important contents of C common content, correct, flexible use of reference, can make the program simple, efficient. I found it in my work. Many people use it just to be of course, in some subtle occasions, it is easy to make mistakes. Most of them are due to this source. Therefore, in this article, I will discuss the reference in this article, I hope to better understand and use the reference to the role of the brick jade. Quote Introduction The reference is an alias of a variable (target), which is exactly the same as the direct operation of the reference. Quote: Type Identifier & Reference Name = Target Variable Name; [Example 1]: Int A; INT & RA = A; / / Define Reference RA, it is a reference to variable A, ie alia name description: (1) & It is not an address operation here, but a logo. (2) Type identifiers refer to the type of target variable. (3) When the declaration is referenced, it must be initialized simultaneously. (4) After the reference declaration is completed, it is equivalent to the target variable name, which is the target original name and reference name, and can no longer use the reference name as an alias of other variable names. RA = 1; equivalent to a = 1; (5) declare a reference, not a new variable, which only indicates that the reference name is an alias of the target variable name, which is not a data type, so reference it itself No storage unit, the system does not assign storage units to the reference. Therefore, the address is requested to be addressed to the target variable. & ras equivalent to & a. (6) Can't establish an array reference. Since array is a collection consisting of several elements, an alias of an array cannot be established. Quote Application 1, reference to an important role as a parameter reference is the parameter of the function. The function parameters pass in the previous C language are values. If there is a large block of data as a parameter transmission, the scheme used is often a pointer, as this can avoid all stacking of the entire data, and can improve the efficiency of the program. But now (C ) has added a choice of equivalent efficiency (in some special cases, it is necessary to choose), is a reference. [Example 2]: Void SWAP (INT & P1, INT & P2) // These functions of this function are referenced to {INT P; P = P1; P1 = P2; p2 = p;} is called in the program This function, at the invocation point of the corresponding main adjustment function, directly as the argument, without any special requirements, without requiring the real parameters. Such as: corresponding to the SWAP function defined above, the corresponding main adjustment function can be written as: main () {INT A, B; CIN >> A >> B; // input A, B two variables of the value SWAP (A, B ); // Directly use the variables A and B as a solid-parap with SWAP function cout << a << '<< b; // output result} The above program is running, if the data 10 20 is input, then output The result is 20 10.

As can be seen from [Example 2]: (1) Transfer reference to function is the same as the effect of the transfer pointer. At this time, the parameter of the modulated function is used as an alias for the actual argument variable or object in the main modulation function, so the operation of the counter-arranging variable in the modulated function is the corresponding target object (at the main) The operation of the modulus of the function. (2) Use the parameters of the reference transfer function, there is no copy of the argument in memory, which is directly for the actual parameters; and the parameters of the general variable transfer function, when the function is called, the formation is required to distribute storage The unit, the variable variable variable is a copy of the real parameter variable; if the object is passed, the copy constructor will also be called. Therefore, when the data passed by the parameter is large, the efficiency of transmitting parameters with general variables with general variables is good. (3) Although the parameter using the pointer as a function can also achieve the effect of using the reference, it is also necessary to give the ginseng storage unit in the modular function, and need to repeat the "* pointer variable name" in the form of operation, This is easy to generate errors and is poorly reading; on the other hand, at the call point of the main adjustment function, the address of the variable must be used as the argument. The reference is easier to use, clearer. If you need to use the reference to improve the efficiency of the program, it is necessary to protect the data that is passed to the function is not changed in a function, and a common reference should be used. 2, often citing often reference declaration: const type identifier & reference name = target variable name; reference to this way, cannot be modified by reference to the value of the target variable, so that the target of the reference is constant, reaching Quote security. [Example 3]: Int a; const INT & ra = a; ra = 1; // error a = 1; // correct this is not only to make the code more robust, and some other aspects. [Example 4]: Assume that there is a function declaration: string foo (); void bar (String & S); then the following expression will be illegal: bar (foo ()); bar ("hello world); reason In the foo () and "Hello World" strings generate a temporary object, in C , these temporary objects are const types. Therefore, the above expression is to try to convert a const type of object to a non-const type, which is illegal. The reference parameters should be customized as constings without CONST. 3. Reference as a return value to return function values ​​to reference, the function is defined as the following format: Type Identifier & Function Name (Description of Types and Types Description) {Functional Body} Description: (1) To reference the return function value The biggest advantage of the definition function is required to return to a function value before the function name is that a copy of the returned value is not generated in the memory. [Example 5] A normal function fn1 (which returns a function value with the return value) in the following program, and another function fn2 returns a function value in a reference method.

#include float tempfloat fn1 (float r); // Declaration FN1FLOAT & FN2 (FLOAT R); // Declarative Function FN2FLOAT FN1 (FLOAT R) // Define Function FN1, it Returns the function value {TEMP = (FLOAT) (R * R * 3.14) (R * R * 3.14) in return value; Return Temp;} FLOAT & FN2 (FLOAT R) // Defines Function FN2, which returns the function value {TEMP = (Float) in a reference mode (r * r * 3.14); return temp;} void main () // main function {float a = fn1 (10.0); // First case, system generates a copy to return value (ie, temporary variable) Float & b = fn1 (10.0); // The second case may be wrong (different C systems have different provisions) // cannot return a temporary variable or a reference FLOAT C = Fn2 (10.0) of the local variable from the called function. // In the third case, the system does not generate the returned value // can return a reference FLOAT & D = Fn2 (10.0); // of a global variable from the modulated function, the system does not generate a copy of the return value. / / You can return a global variable from the modulated function to a reference COUT << a << c << d;} Reference as a return value, must be followed by the following rules: (1) You cannot return a reference to local variables. This can refer to Item 31 of Effective C [1]. The main reason is that the local variable is destroyed after the function returns, so the reference to be returned is a reference to "none", and the program will enter an unknown state. (2) You cannot return a reference to the memory allocated by the internal NEW. This can refer to Item 31 of Effective C [1]. Although there is no passive destruction problem of local variables, it is possible to face other embarrassing situations for this situation (return to the NEW allocation memory). For example, the reference returned by the function is only as a temporary variable, and is not given a actual variable, then the space points indicated by this reference (allocated by NEW) cannot be released, resulting in MEMORY Leak. (3) You can return to a reference to class members, but it is preferably const. This principle can refer to Item 30 of Effective C [1]. The main reason is that when the object's attribute is associated with a business rule, its assignment is often related to certain other attributes or objects, so it is necessary to encapsulate assignment operations in a business rule. If other objects can get a very quite reference (or pointer) of this property, the simple assignment of this property will destroy the integrity of the business rule. (4) References with some operators: stream operators << and >>, these two operators often want to be used continuous, for example: cout << "hello" << Endl; therefore these two operators The return value should be a circle that still supports both operators. Optional other schemes include returning a stream object and returning a stream object pointer. But for returning a stream object, the program must re-(copy) construct a new stream object, that is, two consecutive << operators are actually for different objects! This cannot be accepted.

The << operator cannot be used continuously for returning a stream pointer. Therefore, returning a stream object is the only choice. This unique choice is critical, which illustrates the importance of reference and irreplaceability, maybe this is the reason why the C language introduces this concept. Assignment operator =. Like the operation of the operation, it is possible to use, such as 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 assign. Therefore, reference to the unique return value of this operator. [Example 6] Tests the value of the returned reference to the left value of the assignment expression. #include int p = -1; int = -1; void main () {PUT (0) = 10; // Use the PUT (0) function value as the left value , Equivalent to Vals [0] = 10; PUT (9) = 20; // Taking the PUT (9) function value as the left value, equivalent to VALS [9] = 10; 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 other operators, it is not possible to return to the reference: - * / four operators. They cannot return references, and the Item 23 of Effective C [1] discusses this problem. The main reason is that these four operators do not have Side Effect, so they must construct an object as a return value, and the optional scheme includes returning an object, returns a reference to a local variable, returns a reference to a NEW allocated object, return A static object reference. According to the references mentioned earlier as the three rules of the return value, the second and third programs have been vetoed. Quote for static objects is also due to ((A B) == (C D)) will always cause errors. So only the optional only returns an object. 4. References and polymorphisms are a means of which can produce polymorphic effects except for the pointer. 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; A & REF = B; // The reference REF of the initialized base class object with the derived class object can only be used to access the party object from the base The class inherited, is the base class reference points to the derivation class. If you define a virtual function in the class A, you can generate a polymorphic effect by REF in the Class B renovation. Quote Summary (1) In the reference, it is meaningless to take a certain variable, the purpose of the reference is mainly used to solve the transfer efficiency of block data or objects in the function parameter transmission. problem. (2) Use the parameters of the reference transfer function to ensure that the copies are not generated in parameter transmission, improve the efficiency of the transmission, and ensure the security of the reference delivery is guaranteed by the use of Const. (3) The reference to the pointer is that the pointer is indirectly operated to the variable to which it points to by a pointer variable. The program is used in the program, the readability of the program is poor; the reference itself is the alias of the target variable, and the operation of the reference is the operation of the target variable. (4) Use the reference time.

转载请注明原文地址:https://www.9cbs.com/read-57926.html

New Post(0)