一个好的 C++ 编译器会优化引用吗? [英] Will a good C++ compiler optimize a reference away?
问题描述
我想写一个模板函数,用 std::stack
和一个 T
的实例做一些事情,例如:
I want to write a template function that does something with a std::stack<T>
and an instance of T
, e.g.:
template<class StackType> inline
bool some_func( StackType const &s, typename StackType::value_type const &v ) {
// ...
}
我通过引用传递 v
的原因当然是为了针对 StackType::value_type
是 struct
或 的情况进行优化>class
而不是按值复制整个对象.
The reason I pass v
by reference is of course to optimize for the case where StackType::value_type
is a struct
or class
and not copy an entire object by value.
然而,如果 StackType::value_type
是像 int
这样的简单"类型,那么当然最好直接按值传递.
However, if StackType::value_type
is a "simple" type like int
, then it's of course better simply to pass it by value.
问题是:对于像 int
这样的类型,它会变成 int const&
作为上述函数中的形式参数,编译器是否会优化掉引用和只是按值传递?
The question is: for a type such as int
that would become int const&
as a formal argument in the above function, will the compiler optimize away the reference and simply pass it by value?
推荐答案
我在这里查看 gcc 优化选项 http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
I look in gcc optimization options here http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
实际上您的情况有一个选项:
And actually there is an option for your case:
-fipa-sra
执行聚合的过程间标量替换,删除未使用的参数,并通过值传递的参数替换通过引用传递的参数.
Perform interprocedural scalar replacement of aggregates, removal of unused parameters and replacement of parameters passed by reference by parameters passed by value.
在 -O2、-O3 和 -Os 级别启用
Enabled at levels -O2, -O3 and -Os
据我所知,-O2 是 Linux 上发布版本的常用选项.
As far as I know, -O2 is usual option for release build on linux.
所以,简短的回答是:优秀的编译器之一
这篇关于一个好的 C++ 编译器会优化引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!