C++ reference summary

Reference: It is an alias of a variable (target). The operation of the reference object is exactly the same as the direct operation of the variable.
The declaration method of the reference: type indicator & reference name = target variable name

Defined as follows:

Define reference a, which is a reference to variable b, ie alias
int a;
int &a=b;

Notice:

(1) & is not an address operator here, but an identification

(2) The type identifier refers to the type of the target variable

(3) When declaring a reference, it must be initialized

(4) After the reference is declared, it is equivalent that the target variable has two names, namely the original name of the target and the reference name, and the reference name can no longer be used as an alias for other variable names.

(5) Declaring a reference is not a newly defined variable. It only means that the reference name is an alias of the target variable name. It is not a data type itself, so the reference itself does not occupy a storage unit, and the system does not assign the reference to the reference. storage unit. Therefore: seeking the address of the reference is to seek the address of the target variable. &ra is equivalent to &a.

(6) You cannot create a reference to an array. Because an array is a collection of elements, it is not possible to establish a reference to data with multiple elements.

Referenced apps:

1. Reference as a parameter
(1) Passing a reference to a function has the same effect as passing a pointer. At this time, the formal parameter of the called function is used as an alias of the actual parameter variable or object in the original calling function, so the operation of the formal parameter variable in the called function is to the corresponding target object (in the main function). in the calling function).

(2) The parameters of the function are passed by reference, and there is no copy of the actual parameters in the memory. It operates directly on the actual parameters; while the parameters of the function are passed by general variables, when a function call occurs, it is necessary to allocate storage to the formal parameters unit, the parameter variable is a copy of the actual parameter variable; if an object is passed, the copy constructor will also be called. Therefore, when the data passed by the parameter is large, the efficiency and space occupied by passing the parameter by reference are better than that by using the general variable.

(3) Although using a pointer as a function parameter can also achieve the same effect as using a reference, in the called function, a storage unit must also be allocated to the formal parameter, and the form of "*pointer variable name" needs to be used repeatedly for operations. This is error-prone and the program is less readable; on the other hand, at the call site of the calling function, the address of the variable must be used as an argument. And citations are easier to use and clearer.

If you want to use references to improve the efficiency of your program, but also to protect the data passed to the function from being changed in the function, you should use constant references. 2. Often quoted
  

  Constant reference declaration method: const type identifier & reference name = target variable name;
 
  a reference declared in this way cannot modify the value of the target variable by reference, so that the target of the reference becomes const and the security of reference is achieved .
 For example: Suppose you have the following function declaration:

    string test();

    void bar(string &s);

  Then the following expression would be illegal:

    bar (test ());

    bar(“hello world”);

  The reason is that both foo( ) and the "hello world" string produce a temporary object, and in C++, temporary objects are all of type const. So the above expression is an attempt to convert an object of type const to a non-const type, which is illegal.
  Reference parameters should be defined as const as much as possible when they can be defined as const. 3. Reference as return value
  
 

  To return a function value by reference, define the function in the following format:

    Type identifier & function name (parameter list and type specification)

    {function body}

  illustrate:

  (1) Return the function value by reference. When defining a function, you need to add & before the function name

  (2) The biggest advantage of returning a function value by reference is that there is no copy of the returned value in memory.

Rules to follow:

  (1) A reference to a local variable cannot be returned. This can refer to Item 31 of Effective C++[1]. The main reason is that local variables will be destroyed after the function returns, so the returned reference becomes a "nothing" reference, and the program will enter an unknown state.

  (2) A reference to the memory allocated by new inside the function cannot be returned. This can refer to Item 31 of Effective C++[1]. Although there is no passive destruction of local variables, for this situation (returning a reference to the memory allocated by new inside the function), there are other embarrassing situations. For example, the reference returned by the function only appears as a temporary variable without being assigned an actual variable, then the space pointed to by the reference (allocated by new) cannot be released, that is, it cannot be accessed by the delete[] variable name. This Ang generated in the heap is released. Cause memory leak.

  (3) References to class members can be returned, but preferably const. This principle can refer to Item 30 of Effective C++[1]. The main reason is that when the property of an object is associated with a business rule, its assignment is often related to some other properties or the state of the object, so it is necessary to encapsulate the assignment operation in a business rule. If other objects can obtain a non-const reference (or pointer) to the property, then a simple assignment to the property would violate the integrity of the business rules. (negotiable)

  (4) Reference and overloading of some operators: stream operators << and >>, these two operators are often expected to be used consecutively, for example: cout << "hello" << endl; Therefore, these two operators The return value of should be a stream reference that still supports both operators. Alternative alternatives 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 is unacceptable. The << operator cannot be used continuously for returning a stream pointer. Therefore, returning a stream object reference is the only option. This only choice is crucial, it shows the importance and irreplaceability of references, perhaps this is the reason why the concept of references was introduced in the C++ language. The assignment operator =. This operator, like the stream operator, can be used continuously, 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 continuously assigned. Therefore a reference becomes the only return value option for this operator.
  (5) In some other operators, but must not return a reference: +-*/ four operators. They cannot return references, which is discussed in detail in Item 23 of Effective C++ [1]. The main reason is that these four operators have no side effect, so they must construct an object as the return value. The optional solutions include: returning an object, returning a reference to a local variable, returning a reference to an object allocated by new, returning A static object reference. According to the aforementioned three rules of reference as return value, the 2nd and 3rd solutions are both rejected. References to static objects again cause errors because ((a+b) == (c+d)) will always be true. So the only option left is to return an object.

 4. References and Polymorphism

  References are another means of polymorphism besides pointers. This means that a reference to a base class can point to an instance of its derived class.

    class A;

    class B:public A{ … … }

    B b;

    A &Ref = b;//Initialize the reference of the base class object with the derived class object

  Ref can only be used to access the members inherited from the base class in the derived class object, and the base class reference points to the derived class. If a virtual function is defined in class A, and the virtual function is rewritten in class B, polymorphism can be generated through Ref

Citation Summary

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

  (2) Passing the parameters of a function by reference can ensure that no copies are generated during parameter passing, improve the efficiency of passing, and ensure the safety of passing by reference through the use of const.

  (3) The difference between a reference and a pointer is that after a pointer points to an object through a pointer variable, it operates indirectly on the variable it points to. The use of pointers in the program makes the readability of the program poor; the reference itself is an alias of the target variable, and the operation on the reference is the operation on the target variable.

  (4) Timing of the use of citations. The stream operators << and >>, the return value of the assignment operator =, the parameters of the copy constructor, the parameters of the assignment operator =, and other situations are recommended to use references. .

Reference blog post:
C++ reference summary
original text for more detailed C++ reference summary

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326036119&siteId=291194637