本文介绍了当模板类型是基本参数时,通过引用传递的成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我一直听说,确保最佳效果的良好做法是:I've always heard that a good practice to ensure best performance was to: 传递基本类型( int , double ...)by valuepass fundamental types (int, double...) by valuepass classes by const reference现在,在编译器下使用C ++ 11和完全优化,当通过const引用传递一个基本类型时,是否有开销?Nowadays, using C++11 and full optimizations under a compiler, is there an overhead when one passes a fundamental type by const reference?此外,当 T 为 int 时,template <typename T> inline void f(const T& x);比:template <typename T> inline void f(const T x);推荐答案如果编译器真的内联代码普通的简单模板)就没有什么区别。当函数无法内联并调用外联定义时,问题变得明显。If the compiler is really inlining the code (which is common for simple templates) there will be no difference. The problem becomes apparent when the function cannot be inlined, and the out-of-line definition is called.在这种情况下,传递引用可能涉及在访问变量时的额外解引用(至少第一次,可能多次)。同时,如果参数是按值,编译器可以执行更积极的优化,因为它知道该变量不能在当前函数之外访问/修改。In that case, passing a reference can involve an extra dereference when accessing the variable (at the very least the first time, possibly multiple times) At the same time, the compiler can perform more aggressive optimizations if the argument is by value, since it knows that the variable cannot be accessed/modified outside of the current function. 这篇关于当模板类型是基本参数时,通过引用传递的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-12 15:31