When should I inline, when should I put it in functions.cpp?

Started by
2 comments, last by Tevong 22 years, 6 months ago
should I inline all my class member functions in the same header file by inlining or put them all in a separate function.cpp?
Signed: ___T____
Advertisement
Its all an opinion... my opinoin is:


Inline = Messy;
------------------------------Put THAT in your smoke and pipe it
Inline when the function is small and you''d like the body to replace its usage in every instance. For example:
int min(int a, int b){  return (a < b) ? a : b;} 

This kind of function used to be coded as a C macro, but macros don''t do typechecking (and you have to be careful to parenthesize correctly, or unexpected behaviors could occur. Since it''s such a small function, the overhead of allocating memory on the stack and so forth is so much more than the function body that it''s better to actually place that code everywhere you call min(). In such cases, make the function inline.

Also inline where there may be a lot of compund usage, like arithmetic operators:
class vector3d{public:...inline float &operator[] (int j);inline vector3d &operator*= (float s);// note that the next function is _not_ inlinefriend float &operator* (vector3d &v1, vector3d &v2);...private:  float coords[4];};// inline functionfloat &vector3d::operator[] (int j){  return coords[j % 4];}// inline functionvector3d &vector3d::operator*= (float s){  for(int j = 0; j < 4; ++j) coords[j] *= s;  return *this;}// friend function - dot productfloat &operator* (vector3d &v1, vector3d &v2){  // ignore w-coord; it''s for homogeniety  return (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]);} 

The [] operator is better inlined because it is used so heavily in other operators that in-place expansion speeds up execution remarkably.
A good rule of thumb for deciding whether a function should be declared inline or not is that if the code only takes one line, it should be inline''d, otherwise not. In addition, the inline specifier only requests that the compiler inline the function. If the function is too complex for the compile to resolve, whether it fits on one line or not, the compiler will ignore the inline specifier and generate a function call anyway.

Paradigm Shift 2000
"I am Locutus of Borg. Resistance is Futile." -- Locutus of Borg

This topic is closed to new replies.

Advertisement