(23条消息) C++ 函数返回局部变量地址和引用_最后冰吻free的博客-CSDN博客_c++函数返回地址

PHOTO EMBED

Thu Nov 24 2022 06:10:32 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#include <iostream>

using namespace std;

//不要返回局部变量的引用
//局部变量存放在栈区空间中,函数退出后栈区空间被自动释放
int& print()
{
	int a = 10;
	int &b = a;
	
	return b;	
}

int main()
{
		int &a = print();
		cout<<a<<endl;//第一次编译器会保留函数的返回值
		cout<<a<<endl;//第二次值就会被释放掉了,防止后面使用引用
		return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
content_copyCOPY

https://blog.csdn.net/CodeHouse/article/details/107239188