C++: Pass by value and pass by reference

Pass by value and pass by reference

引用: Variable data type
语法: &引用名 = 已声明的变量名
Use reference as the realization of function parameters to pass by reference
函数参数传递:
Pass by value(One-way value copy, only the value of the actual parameter can be copied to the formal parameter, and the actual participating formal parameters have their own exclusive memory )
Pass by reference: The implementation is the reference transfer (the form participates in the actual parameter sharing memory ), and the actual participation parameter is the same object

Value transfer is used for read operations
Reference transfer is used for write operations
Reference types: pointers, arrays, reference types


Pointer version

Exchange the values ​​of 2 variables
@param pa, int*, pointer
@param pb, int*, pointer

void swap(int* pa,int* pb){
    
    
	int t;
	t = *pa; 
	*pa = *pb; 
	*pb = t;
}

Array version

Exchange the values ​​of 2 variables
@param arr, int[], array

void swap(int arr[]){
    
    
	int t;
	t = arr[0];
	arr[0] = arr[1];
	arr[1] = t;
}

Reference version

Exchange the values ​​of two variables
Parameter binding: &ra = num1, &rb = num2; The
reference is essentially another legal name of the variable
@param ra, int&, reference type
@param rb, int&, reference type

void swap(int &ra, int &rb){
    
    
	int t;
	t = ra; 
	ra = rb; 
	rb = t;
}

Allocate memory

Pointer version : write operation, pass
by reference, the actual parameter uses the address of the variable of this type
Parameter binding: p = &pnum;
@param p, the type is int**, the pointer of the pointer (second-level pointer)

void allocMemory(int* *p){
    
    
	//p= (int*)malloc(sizeof(int)*10);
	*p = new int[10];//为pnum指针指定的空间分配内存
	//赋值操作:(*p)[0] = 1;
}

Reference version : write operation, pass
by reference, the actual parameter uses the variable name of this type
Parameter binding: &p = pnum
@param p:int*&, pointer reference

void allocMemory(int* &p){
    
    
	p = new int[10];
	//赋值操作:p[0] = 1;
}

Main function

int main(){
    
    
	int* pnum;
	//调用指针版本,实参用该类型变量的地址
	allocMemory(&pnum);
	//调用引用版本,实参用该类型的变量名
	allocMemory(pnum);
	
	pnum[0] = 2021;//检验内存是否分配成功
	cout << pnum[0] << endl;
	
	int num1, num2;
  	//int num[2];
  	
	cin >> num1 >> num2;
	//cin >> num[0] >> num[1];
	
	//调用指针版本,实参用该类型变量的地址
	swap(&num1, &num2);
	//调用引用版本,实参用该类型的变量名
	swap(num1, num2);

	//swap(num);//实参数组名

	cout << num1 << endl;
	cout << num2 << endl;
	//cout << num[0] << endl;
	//cout << num[1] << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_51354361/article/details/114780012