为什么编译器在返回对局部变量的局部引用时不警告"returning address of local variable or temporary"?
Why doesn't the compiler warn "returning address of local variable or temporary" when returning a local reference to a local variable?
在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);
}
是的,它仍然是错误的。
编译器无法检测到您正在执行危险(或非法)操作的所有情况。当它找到它们时,它会发出警告,但它无法识别所有案例(也不必识别)。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- 赛通"Cannot take address of memoryview slice"
- C++:寻找"returning address of local variable..."的更正
- 为什么打印 c 样式字符串的'address of index n'会导致子字符串的输出
- 隐式转换产生"error: taking address of temporary"(GCC 与 clang)
- 如何修复警告"the compiler can assume that the address of 'object' will never be NULL"
- 当"taking address of temporary"错误妨碍干净的代码时
- 忽略"taking address of temporary"错误
- "taking address of temporary"警告
- 为什么编译器在返回对局部变量的局部引用时不警告"returning address of local variable or temporary"?
- 有关 C 和 C++ 中的"Address-of operator" (&) 和数组的问题
- 如何避免"taking address of temporary"没有问题?
- 使用 C 字符串会发出警告:"Address of stack memory associated with local variable returned"
- "address of array"的实际用例是什么?
- C++错误:"taking address of temporary array"
- "address of"操作员的性能如何?
- 我的文本数据库程序"Cannot resolve address of overloaded function"