编译器是否优化了按值传递的函数参数? [英] Does the compiler optimize the function parameters passed by value?

查看:24
本文介绍了编译器是否优化了按值传递的函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数,其中参数通过值而不是常量引用传递.此外,让我们假设函数内部只使用了该值,即函数不会尝试修改它.在这种情况下,编译器是否能够确定它可以通过常量引用传递值(出于性能原因)并相应地生成代码?有没有编译器可以做到这一点?

Lets say I have a function where the parameter is passed by value instead of const-reference. Further, lets assume that only the value is used inside the function i.e. the function doesn't try to modify it. In that case will the compiler will be able to figure out that it can pass the value by const-reference (for performance reasons) and generate the code accordingly? Is there any compiler which does that?

推荐答案

如果你传递一个变量而不是一个临时变量,如果它的复制构造函数做了你在运行时会注意到的任何事情,编译器就不能优化掉这个副本程序(可观察的行为":输入/输出,或改变易失性变量).

If you pass a variable instead of a temporary, the compiler is not allowed to optimize away the copy if the copy constructor of it does anything you would notice when running the program ("observable behavior": inputs/outputs, or changing volatile variables).

除此之外,编译器可以自由地做它想做的一切(它只需要类似于可观察行为as-if它根本不会优化).

Apart from that, the compiler is free to do everything it wants (it only needs to resemble the observable behavior as-if it wouldn't have optimized at all).

仅当参数是右值(最临时)时,编译器才被允许优化复制到按值参数,即使复制构造函数具有可观察到的副作用.

Only when the argument is an rvalue (most temporary), the compiler is allowed to optimize the copy to the by-value parameter even if the copy constructor has observable side effects.

这篇关于编译器是否优化了按值传递的函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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