我了解到我们不应该返回指向本地变量的指针或引用。在下面给出的例子中,当我在函数foo内写入
return i;
时,我理解我正在返回对本地变量的引用。在函数外使用该引用将导致未定义的行为。#include <iostream>
const int& foo()
{
int i = 5;
return i;//returning reference to a local variable
}
const int& func()
{
return 5;
}
int main()
{
const int& ref = func();
const int& f = foo();
std::cout<<f<<std::endl; //I know this is undefined behavior because we're using a reference that points to a local variable
std::cout<<ref; //But IS THIS UNDEFINED BEHAVIOR too?
}
我的问题是,对于函数 func
内的返回语句 return 5;
是否同样适用。我知道在 C++17 中有强制复制省略。所以我的问题针对所有现代 C++ 版本(C++11、C++17 等)。这种行为是否取决于 C++ 版本。
特别地,我知道语句 std::cout<<f<<std::endl;
在 main
函数中总是未定义的行为,因为我们正在使用指向局部变量的引用(悬垂引用)。但是语句 std::cout<<ref;
是否也会导致未定义的行为?如果不是,为什么?这里会发生什么。
PS:我可能描述第一个 cout
语句的实际情况是错误的。如果我错了,请纠正我。
const int&
而不是首先返回int
的情况。我不确定临时生命周期延长是否适用于这两种情况,因为您绑定到了一个const
引用。 - Nathan Piersonfunc
的警告:*warning : returning reference to local temporary object [-Wreturn-stack-address]*。输出结果是垃圾。 - Adrian Molefunc() = 6; std::cout << 5 << '\n';
,程序将显示值6,因为对func()
的赋值更改了文字5的值。 - Pete Becker