[Understanding C++] References and the keyword auto

insert image description here

1. Citation

1. The concept of reference

Reference is to take an alias for an existing variable and share a memory space with the variable. Note that the reference type must be the same as the variable type to demonstrate how references are used.

#include <iostream>
using namespace std;

int main()
{
    
    
	int a = 1;
	int& b = a;
	int& c = b;
	int& d = c;
	
	cout << &a << endl;
	cout << &b << endl;
	cout << &c << endl;
	cout << &d << endl;

	return 0;
}

As shown in the above code: we give a an alias b, give b an alias c...that is, b is a reference, c is a reference of b.... In fact, b, c, and d all represent a, and they all share a memory space .
As shown below:
insert image description here

2. Citation use and problems

Note for citations :

  1. reference must be initialized
  2. References cannot be changed
  3. A variable can have multiple references

References can be used as parameters of functions or as return values . Before learning C language, we often use pointers to pass parameters, that is, call by reference to change the value of external variables. After learning references, it will be very convenient for us to only use references to pass parameters.
When returning a reference, it will lead to many problems, here we analyze the following code:

int& Add()
{
    
    
	int n = 0;//静态变量static int a = 0;
	n++;

	return n;
}

int main()
{
    
    
	int ret=Add();
	cout << ret << endl;
	return 0;
}

n becomes 1 in the Add function, and Add returns the reference of n . We use the variable ret to receive the reference of n, that is, the value of n , but there is a problem——after n exits the Add function , if the function stack frame is With sanitization , the value found by the function return reference will be a random value . If the stack frame is not cleaned up, then ret is correct by fluke1. In order to avoid this situation, we can set the n of the Add function as a static variable .
To verify, let's look at the following code again:

int& Add(int x)
{
    
    
	int n = x;
	n++;
	return n;
}

int main()
{
    
    
	int& ret=Add(10);
	cout << ret << endl;

	Add(20);
	rand();
	cout << ret << endl;
	return 0;
}

Assuming that the stack frame is not destroyed after the Add function, the printed result will be 11\n21, but if we call a function to simulate the destruction of the function stack frame , will the result be a random value as we expected ?
insert image description here

Summary
Passing parameters by reference is suitable for most situations.
When returning a value by reference, you need to pay attention to whether the reference object or the function still exists .

Let's take a look at reference usage scenarios and their advantages:
1. References as parameters - (output parameters)
2. References as parameters - (reducing copying and improving efficiency) (large objects/deep copy objects)
3. References as return values ​​- (Reduce copying and improve efficiency) (Large objects/deep copy objects)
4. Reference as return value - modify return value + get return value

Next, let’s talk about the zoom-in, zoom-out, and translation of common references and reference permissions:

int func()
{
    
    
	stctic int a=0;
	a++;
	return a;
}
int main()
{
    
    
	//引用的权限可以平移和缩小不可以放大
	int a = 0;
	int& b = a;//平移
	const int& c = a;//缩小
	++a;
	++c;//放大


	const int a = 10;
	int& b = a;//只能给变量取别名

	double c = 3.14;
	int& d = c;//引用的类型需要匹配
	const int& e = c;//类型转换会创建临时变量 临时变量具有常量性质

	int& ret=func();//权限放大
	return 0;
}

At the grammatical level, references do not use space knowledge to obtain an alias for variables, but from the perspective of the underlying assembly instructions, references are used in a manner similar to pointers.

3. Comparison of references and pointers

References and pointers differ in a number of ways:

  1. References need to be initialized, pointers do not
  2. References cannot be modified, pointers can
  3. There are null pointers, no null references
  4. References are safer, and pointers may have wild pointers and out-of-bounds situations
  5. The reference in sizeof is the byte size of the type, and the pointer judges the number of bytes based on the number of bits in the machine
  6. References syntactically define an alias for a variable, pointers store the address of a variable
  7. multilevel pointers no multilevel references
  8. The pointer needs to be dereferenced according to the address, and the reference is handled by the compiler itself

2. Keyword auto

auto can automatically identify the type. When the type is too complicated and lengthy, auto is very convenient to use.

int main()
{
    
    
	int a = 1;
	auto b = 10;
	auto c = 3.14;
}

When defining multiple variables on the same line, you need to pay attention to the fact that the variable types on the same line must be consistent, otherwise auto will not be able to identify them correctly:

int main()
{
    
    
	auto a = 1, b = 2; 
 	auto c = 3, d = 4.0;//类型不同
}

auto cannot yet be used as a parameter of a function and define an array

Auto also has an important application - range for loop,
which provides a simpler method of for traversal. According to the colon ":", it is divided into two parts: the first part is the variable used for iteration in the range, and the second part represents The range to iterate over.

int main()
{
    
    

	int arr[] = {
    
     0,1,2,3,4,5,6 };

	for (auto x : arr)
		cout << x << endl;
}

Guess you like

Origin blog.csdn.net/qq_43289447/article/details/130229317