It seems that if you want a class member function to be inlined during the compilation phase, the function should be defined inside the class declaration block.
This is not true. A function defined inside a class definition is implicitly marked as inline
. But you do not need to define the function inside the class so that it is inline
, you can explicitly request it:
struct X { void f(); }; inline void f() {}
On the other hand, the inline
does not mean that the function will be built-in, but rather can be defined in several translation units, i.e. if multiple translation units include the same header that contains this definition, the linker does not fail with a multiple definition error.
Now, with the actual embedding, the compiler can solve the built-in or not some function, regardless of whether the function is declared as inline
, provided that it sees the definition of this function (the code that it will be embedded), which is the reason that the general functions that need to be built in must be defined in the header (either inside the class definition, or marked inline
externally.
In addition, new tools can perform whole-program optimizations or other link-time optimizations, with which the linker can also decide what function should be built-in. In this case, the definition of the function should not be visible on the call site, so it can be defined inside the .cpp file. But if you really want the function to be built-in, it is better not to depend on this function and just define the function in the header.
source share