const ref传递整数类型的好处是什么? [英] What are the benefits to passing integral types by const ref

查看:508
本文介绍了const ref传递整数类型的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:通过const引用传递一个整数类型是有益的,而不是简单的值。

The question: Is there benefit to passing an integral type by const reference as opposed to simply by value.

void foo(const int& n); // case #1

vs

void foo(int n); // case #2

对于用户定义的类型,答案是清楚的,情况#1避免了不必要的复制确保对象的一致性。然而在上面的情况下,引用和整数(至少在我的系统上)是相同的大小,所以我不能想象有多少不同的方面需要花费函数调用(由于复制)。但是,我的问题真的与编译器内联函数有关:

The answer is clear for user defined types, case #1 avoids needless copying while ensuring the constness of the object. However in the above case, the reference and the integer (at least on my system) are the same size, so I can't imagine there being a whole lot of difference in terms of how long it takes for the function call (due to copying). However, my question is really related to the compiler inlining the function:

对于非常小的内联函数,编译器必须在case#2中复制整数?通过让编译器知道我们不会改变引用,它可以内联函数调用,而不需要不必要的复制整数?

For very small inline functions, will the compiler have to make a copy of the integer in case #2? By letting the compiler know we won't change the reference can it inline the function call without needless copying of the integer?

欢迎任何建议。

推荐答案

通过const ref传递一个内置的int类型实际上是一个小的去优化。至少对于非内联函数。编译器可能必须实际传递一个必须被解引用以获取值的指针。你可能认为它总是可以优化这个,但是别名规则和支持单独编译的需要可能会强制编译器的手。

Passing a built-in int type by const ref will actually be a minor de-optimization (generally). At least for a non-inline function. The compiler may have to actually pass a pointer that has to be de-referenced to get the value. You might think it could always optimize this away, but aliasing rules and the need to support separate compilation might force the compiler's hand.

但是,对于你的第二个问题: p>

However, for your secondary question:


对于非常小的内联函数,编译器必须在case#2中创建一个整数的副本吗?通过让编译器知道我们不会改变引用,它可以内联函数调用而不需要复制整数?

For very small inline functions, will the compiler have to make a copy of the integer in case #2? By letting the compiler know we won't change the reference can it inline the function call without needless copying of the integer?

编译器应该能够在语义允许的情况下优化离开副本或解引用,因为在那种情况下,编译器完全知道调用点的状态和函数实现。它可能只是加载值到一个寄存器有它的方式,只是使用寄存器的东西,当它完成参数。当然,所有这一切都非常依赖于函数的实际实现。

The compiler should be able to optimize away the copy or the dereference if semantics allow it, since in that situation the compiler has full knowledge of the state at the call site and the function implementation. It'll likely just load the value into a register have its way with it and just use the register for something else when it's done with the parameter. Of course,all this is very dependent on the actual implementation of the function.

这篇关于const ref传递整数类型的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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