在C ++中,是不是通过引用传递一个const bool? [英] In C++, is it bad to pass a const bool by reference?

查看:431
本文介绍了在C ++中,是不是通过引用传递一个const bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实际环境中,使用gcc或MS Visual Studio,传递与const引用相同大小或小于int的值类型是不好的。

In a practical environment, using gcc or MS Visual Studio, is it bad to pass the value types which are the same size or less than an int by const reference ?

ie是不好写这样的函数:

i.e. is it bad to write such a function:

void f(const bool& b);

void f(const char& c);

而不是:

void f(bool b);

void f(char c);

我问的原因是我在这些情况下看不到传递引用的好处,

The reason I am asking is that I do not see the benefit of passing a reference in these cases but maybe I am missing something.

推荐答案

这可能有点不好,或者根本没有效果存储原始值,优化器有多好,以及如何决定如何处理您的代码)。

It may be slightly bad, or it may not have an effect at all (depends on where the original value is stored, how good the optimizer is, and how it decides to treat your code).

标准不要求如何实现引用,但实际上编译器使用指针实现引用。因此,在一般情况下,将使用 bool * 实现 bool& ,这意味着访问 bool 你每次需要一个额外的指针解引用。由于 bool 不大于指针,因此不会减少内存占用或减少字节复制以抵消此缺点。

The standard doesn't mandate how references are to be implemented, but in practice compilers implement references using pointers. Therefore in the general case a bool& would be implemented using a bool*, which means that to access the bool you need an extra pointer dereference each time. Since a bool is no bigger than a pointer, there's no reduced memory footprint or less byte copying to offset this drawback.

因此,接受的做法是将原语作为值传递,因为它更高效。当然,虽然传递这样的引用不会真的炸毁任何东西,除非你访问循环中的值可能甚至不会导致任何可测量的差异。

As a result the accepted practice is to pass primitives around as values since it's more efficient. Of course although passing such around as references won't really blow up anything, and unless you are accessing the value inside a loop will probably not even result in any measurable difference.

这篇关于在C ++中,是不是通过引用传递一个const bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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