2

I'd like to know what is the best style to use inside my C++ library to manage function's parameters that are input-only:

void f(int a)
{
   // ...
}
void f(const int& a)
{
   // ...
}

I know that I should use the second one when I want to pass parameters that are classes or struct, but what about small values?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
user3040937
  • 81
  • 10
  • If the parameter gets changed in a different thread, there's a semantic difference between the two forms. – Kerrek SB Dec 01 '13 at 10:49
  • @KerrekSB:- Yes it struck my mind the moment I typed it thats why I deleted my comment! – Rahul Tripathi Dec 01 '13 at 10:49
  • This question has already been asked, check it out: http://stackoverflow.com/questions/3009543/passing-integers-as-constant-references-versus-copying – mcserep Dec 01 '13 at 10:53
  • You may also be interested in the rules of thumb presented in [this answer](http://stackoverflow.com/a/2139254/2513200) – Hulk Dec 01 '13 at 10:55

3 Answers3

2

When you are using Pass by value for structs where the copying is cheap then there is an additional advantage that the compiler may assume that the objects don't alias ie they are not the same objects. But when you are using pass-by-reference the compiler cannot assume that always.

You may want to check Want Speed? Pass by Value. and How to pass objects to functions in C++?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

Semantics first.

If you need to modify the value, including stealing from it, or need a snapshot of the value, then make a copy of it.

In any other case, using const& is just fine.

As for optimization ? Measure first.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

In case of small values, it is a matter of personal preference. The important thing is to unify your parameter style.