如果编译器为什么未定义行为,为什么会给出有关返回对本地堆栈变量的引用的警告? [英] Why do compilers give a warning about returning a reference to a local stack variable if it is undefined behaviour?
问题描述
C ++标准指出,返回对局部变量的引用(在堆栈上)是未定义的行为,因此为什么许多(如果不是全部)当前的编译器仅对 给出警告?
The C++ standard states that returning reference to a local variable (on the stack) is undefined behaviour, so why do many (if not all) of the current compilers only give a warning for doing so?
struct A{
};
A& foo()
{
A a;
return a; //gcc and VS2008 both give this a warning, but not a compiler error
}
让编译器仅对此警告给出错误而不是警告会更好吗?
Are there any great advantages to allowing this code to compile with just a warning?
仅通过警告就可以编译此代码有很大的优势吗?
Please note that this is not about a const
reference which could lengthen the lifetime of the temporary to the lifetime of the reference itself.
请注意,这与 const
引用无关,它可以将临时变量的寿命延长到引用的寿命
推荐答案
从编译器的角度来看,几乎不可能验证是否要返回对临时变量的引用。如果该标准要求将其诊断为错误,那么编写编译器几乎是不可能的。考虑:
bool not_so_random() { return true; }
int& foo( int x ) {
static int s = 10;
int *p = &s;
if ( !not_so_random() ) {
p = &x;
}
return *p;
}
The above program is correct and safe to run, in our current implementation it is guaranteed that foo
will return a reference to a static
variable, which is safe. But from a compiler perspective (and with separate compilation in place, where the implementation of not_so_random()
is not accessible, the compiler cannot know that the program is well-formed.
以上程序正确且安全运行,在我们当前的实现中确保 foo
将返回对 static
变量的引用,这是安全的。但是从编译器的角度(以及单独进行编译的情况下,无法访问 not_so_random()
的实现,编译器无法知道程序的格式是否正确。 / p>
这是一个玩具示例,但是您可以想象类似的代码,但返回路径不同,其中 p
可能是指返回 * p
的所有路径中都有不同的长期对象。
This is a toy example, but you can imagine similar code, with different return paths, where p
might refer to different long-lived objects in all paths that return *p
.
这篇关于如果编译器为什么未定义行为,为什么会给出有关返回对本地堆栈变量的引用的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!