gpt4 book ai didi

c++ - 从函数返回局部变量的引用不会出错

转载 作者:行者123 更新时间:2023-11-28 08:00:14 25 4
gpt4 key购买 nike

#include<iostream>
#include<conio.h>

using namespace std;

/* test class: created the reference of
abc class locally in function getRef()
and returned the reference.*/

class abc {
int var;

public:
abc():var(5) {}
abc(int v):var(v) {}
abc & getRef() {
abc myref(9);
return myref;
}
void disp() {
cout<<var<<endl;
}
};

int main() {
abc a;
abc b=a.getRef();
b.disp(); /* this statement executed perfectly.
I think compiler should throw error here. */
getch();
return 0;
}

编译器应该抛出编译错误。请解释一下?

最佳答案

编译器不应该标记 b.disp();作为错误,因为那不是错误所在。错误在 return myref; ,这不是硬错误的原因是通常很难确定对象的生命周期是否在 return 之后结束。 .在这种情况下,这很容易,一些编译器确实会尝试对此发出警告。检查您的警告级别。

编辑:顺便说一下,对于 gcc,警告是默认启用的,看起来像“警告:返回对局部变量 '...' 的引用”。

关于c++ - 从函数返回局部变量的引用不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com