Alex Rivera | Logout

In C++, is it bad to pass a const bool by reference?

Asked 2012-08-13T10:35:20.143
24

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 ?

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

void f(const bool& b);

or

void f(const char& c);

rather than:

void f(bool b);

or

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.

Edit
Report

2 Answers

27

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).

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.

answered 2012-08-13T10:38:59.073
0

Although in theory it won't be a good idea, as references are usually implemented using pointers. But nevertheless every reasonable compiler should be smart enough to recognize the indifference in semantics between by-const-reference and by-value for fundamental types.

Often you don't have a choice if you have some kind of templated interface that has to work for complex types and fundamental types and you don't want excessive specialization overhead (simplest example: std::vector). But if you have a choice, then passing fundamental types by-value should be preferred.

answered 2012-08-13T10:42:27.923

Your Answer