The difference between options 2 and 3 is that in the second case, the function will be internal to the translation unit. If a function is defined only in cpp, it should be an option (which is roughly equivalent to an unnamed namespace, which is the fourth option to consider, again roughly equivalent to 3).
If the function should be used by different translation units, then you should go with option 2. The function will be compiled once (if you do not mark it as inline and provide a definition in the header), and with option 3 the compiler will create an internal copy of it in each translation unit .
As option 1, I would avoid this. In Java or C #, you are forced to use classes everywhere, and you end up with utility classes when operations are not very well matched with the paradigm of the object. On the other hand, in C ++ you can provide these operations as functions that allow you to stand freely, and there is no need to add an additional layer. If you choose a utility class, be sure to turn off object creation.
Whether functions are at the class or namespace level will affect the search and this will affect the user code. Static member functions should always be qualified with the class name, unless you are inside the scope of the class, while there are different ways to include namespace functions in the scope. As an illustrative example, consider a bunch of mathematical helper functions and a call code:
double do_maths( double x ) { using namespace math; return my_sqrt( x ) * cube_root(x); } // alternatively with an utility class: double do_maths( double x ) { return math::my_sqrt(x) * math::cube_root(x); }
Which one is easier for you to read is a completely different story, but I prefer the first: inside the function, I can select a namespace and then just focus on operations and ignore the search problems.
David RodrΓguez - dribeas
source share