0

Example 1.

void f(int a);

Example 2 (constant type reference).

void f(const int& a);

Is it better to use the second example because we don't create a copy of an argument object within a function? But why in most cases, even companies, use exactly the first example? I know about big objects - via the second example we can save some memory. I'm asking about ordinary types in c++.

anil shrestha
  • 2,136
  • 2
  • 12
  • 26
gitlng
  • 5
  • 1
  • I know the difference, but why I always see that everyone uses `void f(int a)` case if even they don't change the `a` argument? – gitlng Apr 30 '21 at 06:22
  • For simple types creating reference is heavier operation than creating copy, So for double, int and some other simple types it is better to use copy rather than const reference – Deumaudit Apr 30 '21 at 06:26
  • Depending on what's in your function, access by refernce can be less cache coherent than access by value. – George Apr 30 '21 at 07:03

1 Answers1

0

Technically, a reference passed as function argument will be a pointer, itβ€˜s just some syntactic sugar which makes the reference a bit different to handle compared to a pointer.

Memory wise, the size of an int is 32 bit on most common platforms. The size of a pointer (and thus also the size of a reference passed as argument) is 64 bit on a 64 bit platform and 32 bit on a 32 bit platform.

So passing a reference to a POD might even involve more data being copied compared to passing a copy. So there is no performance gain to expect passing an int by const reference instead of by value. And the function signature looks slightly better readable

PluginPenguin
  • 1,576
  • 11
  • 25