I’ve read about how it is usually best not to define anything in header files because redundant copies are made for every other file that includes the header file. However, in the case of static inline methods, it appears that I have to define it on the spot (at least visual studio 2010 doesn’t let me do that). So if I write an interface at the header file, I can’t define the static inline method out side of the class definition or at the .cpp file.
So, should I bother to use static inline methods at all? And a relate question: Should I even define anything method or variable in a header file (what about constants)?
Anyway, strangely, it’s not something that’s covered in great detail in my C++ books.
Edit: I read through similar questions about static inline methods but none of them seem to directly address this issue.
This can be achieved in 3 possible ways:
inlineorstaticor#1i.e: Marking the functioninlineis the correct way to this without breaking the One Definition Rule.In both
#2each Translation Unit will contain it’s own version of the function, and the program will contain several different versions of the function thus leading to a increase in size of the generated binary.i.e: For a
staticfunctionfun(),&funwill be different in each translation unit, and the program will containNdifferent versions of the function.Also, If the function contains static local variables then there will be
Ndifferent static local variables, one for each function instance.An
inlinefunction has external linkage.When you mark a function
inlinethe function will have the same address in all translation units. Also, Static locals and string literals defined within the body of an inline function are treated as the same object across translation units.In short, a inline function will have the same address across all translation units.
The
statickeyword forces the function to have a internal linkage.Each instance of function defined as inline is treated as a separate function and each instance has its own copy of static locals and string literals. Thus, this would be similar to
#2.Note:
The standard mandates that all definitions of
inlinefunction in an user program You must have the exact same definition in all translation units in which the function is used or called.Relevant Standerdese references:
C++03 Standard
3.2 One definition rule:
Para 3:
7.1.2 Function specifiers
Para 4: