当模板类型是基本参数时,通过引用传递的成本 [英] Cost of passing by reference when a template type is fundamental

查看:256
本文介绍了当模板类型是基本参数时,通过引用传递的成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听说,确保最佳效果的良好做法是:

I've always heard that a good practice to ensure best performance was to:


  • 传递基本类型( int double ...)by value

  • <
  • pass fundamental types (int, double...) by value
  • pass 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.

这篇关于当模板类型是基本参数时,通过引用传递的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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