I have the following code:
#include <iostream>
void f(int &x) {
x = 5;
}
int main() {
int x;
f(x);
std::cout << x << std::endl;
return 0;
}
这段代码在C++中是否会引发未定义行为?g++编译它时没有任何警告,并且代码打印出了5
(是否符合预期?)。
I have the following code:
#include <iostream>
void f(int &x) {
x = 5;
}
int main() {
int x;
f(x);
std::cout << x << std::endl;
return 0;
}
这段代码在C++中是否会引发未定义行为?g++编译它时没有任何警告,并且代码打印出了5
(是否符合预期?)。
void f(int& x)
,int&
是引用类型,它会改变绑定到的变量的值,而不是复制它。int& f() {
int x = 5;
return x; //return a reference of a variable that will not exist
//after f finished
}
int main() {
std::cout << f() << std::endl; //undefined behavior
}
这是未定义的行为,因为引用不负责保持它们所引用的分配数据有效,引用只在值有效时更改和读取值。因此,在 f()
完成后,引用将指向无效的内存。
5
、0
和cout
行中x
的 rvalue-to-lvalue 转换的结果)。但我只是试图给出一个更精确的“使用”定义。 - Kerrek SB