c++简单引用类型函数
int& lameness()
{
int h=66;
return h;
}
int main()
{
int c;
c = lameness();
cout<<"c is "<<c<< endl;
system("pause");
return 0;
}
为什么这有效? int h 是一个局部变量,一旦退出函数作用域,h 不应该被销毁吗?
如果我将我的功能更改为此,它就会在没有警告的情况下工作。这在某种程度上更安全吗? :
int& lameness()
{
int h=66;
int &a = h;
return a;
}
int& lameness()
{
int h=66;
return h;
}
int main()
{
int c;
c = lameness();
cout<<"c is "<<c<< endl;
system("pause");
return 0;
}
Why does this work? int h is a local variable and shouldnt h be destroy once it exits function scope?
If i change my function to this it works without warning. Is this safer in any way?
:
int& lameness()
{
int h=66;
int &a = h;
return a;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。但未定义行为的美妙之处在于,实际发生的事情是……未定义的。销毁 int 实际上根本不涉及执行任何操作,因此如果没有任何内容重用堆栈上的该位置,则该值仍将存在。这就是这种事情如此令人沮丧的原因——通常它看起来很有效,直到你做了一些小的、看似无关的改变,它就不再起作用了!
Yes. But the wonderful thing about undefined behavior is that what actually happens is... undefined. Destroying an
int
actually doesn't involve doing anything at all, so if nothing reuses that spot on the stack, the value is going to still be there. That's what makes this kind of thing so frustrating -- often it seems to work, until you make some small, seemingly unrelated change and it stops working!它的工作原理是巧合,检查一下:
基本上,它返回了正确的值,因为内存仍然设置为该值 价值。将来有时,情况可能并非如此。不要这样做。
It works by coincidence, check this:
Basically, it returned the right value due to the memory still being set to that value. Sometimes in the future, that might not be the case. Don't do this.
它不起作用。这是未定义的行为。您的怀疑是正确的:
lameness
函数是一个错误,一些编译器会将其标记为错误。尽管如此,编译器可能“符合”并且仍然“允许”此代码......这就是 C 和 C++ 的“跛行”。It does not work. It is undefined behavior. Your skepticism was right on: the
lameness
function is an error, and some compilers would flag it as such. Nonetheless, a compiler may be "conforming" and still "allow" this code...such is the "lameness" of C and C++.它被摧毁了。它之所以能起作用,是因为在打印该值时,存储 h 的内存尚未被覆盖。
It is destroyed. It happens to work because memory that h was stored in hasn't been overwritten by the time you print the value.
它只是巧合地对您起作用,并且因为您的代码在执行其他操作之前会获取引用中的值的副本。不保证它能工作。
你可以看到它失败了:
当然,我不得不忽略编译警告:
输出是:
发生这种情况是因为当
c
被传递到 I/O 系统时,曾经的空间 < lameness() 中的 code>h 已被其他变量重用,从而刮掉了存储在空间中的66
。事实上,即使你的原始代码在我的机器上也会产生 0。It only works for you by coincidence, and because your code takes a copy of the value in the reference before doing anything else. It is not guaranteed to work.
You could see it failing with:
Of course, I had to ignore compilation warnings:
The output was:
This happens because by the time
c
is passed to the I/O system, the space that was onceh
inlameness()
has been reused for other variables, thus scratching the66
that was stored in the space. In fact, even your original code produces 0 on my machine.