fxa*_*xam 5 c++ visual-studio-2010
在Visual Studio 2010中编译以下代码时会发生这种情况.我的问题是:如果函数返回局部变量的地址,C++编译器将发出警告,但为什么在返回本地变量的本地引用时不会发出警告?
它仍然是错误的(返回本地变量的本地引用),但只是编译器无法检测到它?检查'num'和'r'的地址表明它们共享相同的内存位置.
#include <iostream>
using namespace std;
int & intReference() {
int num = 5;
int &r = num;
cout << "\nAddress of num: " << #
//return num; // Compiler warning: C4172: returning address of local variable or temporary
return r; // No warning?
}
void main() {
int &k = intReference();
cout << "\nk = " << k; // 5
cout << "\nAddress of k: " << &k; // same address as num
char c;
cin.get(c);
}
Run Code Online (Sandbox Code Playgroud)
是的,它仍然是错的.
编译器无法检测到您正在执行危险(或非法)操作的所有情况.它会在找到它们时发出警告,但它无法识别所有情况(并且不必).
| 归档时间: |
|
| 查看次数: |
1318 次 |
| 最近记录: |