为什么在c ++中的函数可以返回堆栈值 [英] Why function in c++ can return stack values

查看:92
本文介绍了为什么在c ++中的函数可以返回堆栈值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

class C {
  ...
};

const C f() {
    C ret;
    cout << &ret << endl;
    return ret;
}

int main() {
    C value = f();
    cout << &value << endl;
}


result: // note the address are the same
0x7ffdd24b26e0
0x7ffdd24b26e0

函数f()和变量'value'中的变量'ret'具有相同的内存地址,因此'value'不是'ret' 。变量'ret'是一个堆栈变量,所以它应该在f()返回后无效。那么为什么c ++允许在函数中返回一个堆栈值?

The variable 'ret' in function f() and variable 'value' has the same memory address so it seems 'value' is not a copy of 'ret'. The variable 'ret' is a stack variable so it should be invalidated after f() returns. So why c++ allow returning a stack value inside a function?

g ++版本:

g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4


推荐答案

ret和value的地址相同的原因是所谓的返回值优化(Return Value Optimization,RVO)。这意味着在这种情况下不会执行副本。注意,你不能依赖这个,因为它不会发生(虽然这将随着C + + 17 [至少当前的草案])。

The reason for the address of ret and value being the same is the so called Return Value Optimization (RVO). It means that in this case a copy is not going to be performed. Note however, that you can not rely on this, as it is not bound to happen (although that will change with C++17 [at least the current draft]).

https://en.wikipedia.org/wiki/Return_value_optimization

这篇关于为什么在c ++中的函数可以返回堆栈值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆