use*_*570 5 c++ reference function local
我读到我们不应该返回局部变量的指针或引用。因此,在下面给出的示例中,我知道当我编写:return i;inside function时foo,我返回对局部变量的引用。在函数外部使用该引用将导致未定义的行为。
#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?
}
Run Code Online (Sandbox Code Playgroud)
return 5;我的问题是,对于function 内部的return 语句是否同样适用func。我知道在 C++17 中存在强制复制 elison。所以我的问题针对所有现代 C++ 版本(C++11、C++17 等)。该行为是否取决于 C++ 版本/有所不同。
std::cout<<f<<std::endl;特别是,我知道里面的语句main始终是未定义的行为,因为我们使用指向局部变量的引用(悬空)。但该声明是否std::cout<<ref;也会导致未定义的行为。如果不是,为什么以及这里会发生什么。
PS:我在第一个声明中描述实际发生的情况cout也可能是错误的。所以如果我错了请纠正我。
返回对本地 int 变量的引用始终是未定义的行为
从技术上讲没有。返回对局部变量(无论类型如何)的引用本身绝不是未定义的行为。但是这样返回的引用将始终是无效的(如果变量是非静态的),并且通过无效引用进行间接访问始终是未定义的行为。
Run Code Online (Sandbox Code Playgroud)const int& func() { return 5; } int main() { const int& ref = func(); std::cout<<ref; //But IS THIS UNDEFINED BEHAVIOR too? }
是的。您通过无效引用间接进行操作,并且行为未定义。