C ++: is it ok to pass a reference to a function

Arrays can be passed as a pointer to a function or even as a reference. Passing it as a reference gives an alias by which the sizeof and count operators will work. This makes following the link above.

However, going through a sign seems to be the norm in books. What for? Is there something I especially need to know about passing by reference for arrays?

+5
source share
2 answers

Passing by reference means that your function can only accept arrays of a fixed size (therefore, it knows their size, because the compiler uses it). Passing a pointer means otherwise. In addition, passing a pointer allows you to go nullptr , for better or for worse.

+5
source

I usually use std::vector and like to pass by reference to const. However, if my api can be called at some point by c-code, using pass by const-pointer may make sense, although you also need to send the size. If a function can be called using std::array or std::vector , you can decide to send a pointer (and size) or a set of iterators (start / end).

If we are talking about using std :: array, the template argument requires the size of the array. This will mean a normal function, you need a fixed size:

 void myfunc( const std::array<int, 5>& mydata ){...} 

However, if we perform a template function, template size, this is no longer a problem.

 template<unsigned int SZ> void myfunc(const std::array<int, SZ>& mydata) {...} 

If we are talking about c-style arrays allocated by stacks ... Good C ++ style prefers std :: array / std :: vector for c-style arrays. I would recommend reading the C ++ Coding Standard from Herb Sutter , chapter 77 on page 152 talks about the subject. When using c-style arrays, sending a pointer and size is the standard way to jump.

+1
source

Source: https://habr.com/ru/post/1243755/


All Articles