Reference &, the use of reference, constant reference, reference and polymorphism, the difference between reference and pointer

  1. What is a "reference"? What issues should be paid attention to when declaring and using "reference"?

Answer: A reference is an "alias" of a target variable, and the operation of the application is exactly the same as the direct operation of the variable. When declaring a reference, remember to initialize it. After the reference is declared, it is equivalent to the target variable name having two names, namely the original name of the target and the reference name. The reference name cannot be used as an alias for other variable names. Declaring a reference does not mean that a variable is newly defined. 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 allocate a storage unit to the reference. A reference to an array cannot be created.

  1. What are the characteristics of having a "reference" as a function 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 parameter of a function 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.

  1. When do you need to use "constant references"? 

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. Constant reference declaration method: const type identifier & reference name = target variable name;

Example 1

int a;

constint&ra = a;

ra = 1; // error

a = 1; // correct

Example 2

string foo( );

void bar(string&s)

// then the following expression would be illegal:

bar(foo( ));

bar("hello world");

The reason is that both foo( ) and the "hello world" string produce a temporary object, and in C++, these temporary objects are 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.

  1. Format, benefits, and rules for using "reference" as a function return type?

Format:

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

{

// function body

}

Benefit: No copy of the returned value is made in memory; (Note: It is for this reason that it is not advisable to return a reference to a local variable. Because with the end of the local variable lifetime, the corresponding reference is also will fail, resulting in a runtime error!

Notice:

(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) The reference to the memory allocated by new inside the function cannot be returned (pay attention to this, many people don't realize it, haha...). 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, resulting in a 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.

(4) The return value of stream operator overloading is declared as "reference":

Stream operators << and >>, these two operators are often expected to be used consecutively, for example: cout <<"hello" << endl; so the return value of these two operators should be one that still supports these two operations A stream reference for the character. 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.

Example 3

#include <iostream.h>

int&put(int n);

int waltz [10];

int error = -1;

void main()

{

put(0) = 10; // use the value of the put(0) function as the lvalue, which is equivalent to vals[0]=10;

put(9) = 20; // use the put(9) function value as the lvalue, 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, 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.

  1. How does "reference" relate to 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 (see: Class polymorphism and the use of virtual functions in C++).

Example 4

copy code

Class A;

Class B : Class A

{

// ...

};

B b;

A&ref= b;

  1. What is the difference between a "reference" and a pointer?

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. In addition, it is the difference between passing ref and pointer to the function mentioned above.

  1. When do you need a "reference"?

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.

Guess you like

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