函数参数列表中的函数调用是否会加深堆栈?
调用 F(argument_expression)
时,是否在将 F 压入堆栈之前评估 argument_expression
?
例如,当调用F(G(H(arg)))
时,编译器是否首先将H压入堆栈,计算H,弹出,然后将G压入堆栈,等等?还是先压栈F,然后压G,再压H,最后弹出3层?
另外,一种方法比另一种方法更快吗?
When calling F(argument_expression)
, is argument_expression
evaluated before pushing the stack for F?
For example, when calling F(G(H(arg)))
, does the compiler first push the stack for H, evaluate H, pop, then push the stack for G, etc? Or does it first push the stack for F, then for G, then for H, then pop back up 3 layers?
Also, is one way any faster than the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您实际上问了两个正交问题。
评估的概念是从程序员的角度出发的,在本例中,C++ 标准对此进行了明确的定义。是的,函数的参数总是在调用该函数之前评估。
但是,该标准没有指定如何管理堆栈。编译器可以自由地采用您建议的任何一种方法。当然,可能需要第三种选择,即直接内联一个或多个嵌套函数。可能还有其他选择。
You've actually asked two orthogonal questions.
The concept of evaluation is pitched at the programmer's vantage point, and in this case, is well-defined by the C++ standard. Yes, the argument to a function is always evaluated before that function is called.
However, the standard does not specify how the stack should be managed. The compiler is free to take either of the approaches that you've suggested. Of course, it may take a third option, which is to directly inline one or more of your nested functions. There are probably other alternatives.
根据规范,在被调用的函数可以运行之前,参数将被完全评估。
即:在您的示例中,
H(arg)
将在G(H(arg) 的结果)
运行之前完全评估。在任何给定时间,您都会具有一级堆栈深度。
The parameters are fully evaluated before the called function can run, per spec.
I.e.: In your example,
H(arg)
will be fully evaluated beforeG(result of H(arg))
can run, etc.At any given time you'll have one-level depth of the stack.
不,它们是按顺序评估的(在本例中只有一帧深度)。
No, they are evaluated sequentially (only one frame-deep in this case).
这取决于你推 H、G、F 是什么意思
本质上它是这样发生的:
F的返回值被压入,一个临时变量被压入,然后G被压入(它的返回值和一个临时变量),最后所有的H被压入,求值和弹出。然后是 G,最后是 F。
为了性能,如果使用参数表达式,它应该会更快。因为它不应该包含任何跳转。
It depends what do you mean by pushing H,G,F
Essential it happens this way
The return value of F is pushed and a temp variable then G is pushed (its return value and a temp variable ) finally all H is pushed, evaluated and poped. then G and finally F.
for performance if you use argument expression it should be faster. since it should not contain any jumps.