True. But this is the internet. Without pointless discussions what else would there be? ;P
And there's nothing wrong with helping someone understand how inlining works.
Disch: member functions are typically the first to get inlined. You'd have to try really hard (or do something really stupid) for the compiler not to inline the function as described by the poster. |
By "try really hard" do you mean "put the implementation in a cpp file"? Because that's all it takes.
The key concept here is that inline functions have to be expanded in the
compiling process... whereas function bodies existing in other cpp files are not seen until the
linking process (which only occurs after all individual files have been compiled). Hence a.cpp can't* inline a function that is defined in b.cpp.
*(I use the word "can't" here. Really you can, but it involves some trickery that not all common use compilers do yet).
Besides -- in C++ inline functions are pretty much expected to be in the header anyway.
To prove my point... try compiling the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
////////////////////////
// in a.h
void func();
////////////////////////
// in a.cpp
#include "a.h"
#include <iostream>
inline void func()
{
std::cout << "foobar";
}
////////////////////////
// in main.cpp
#include "a.h"
int main()
{
func();
return 0;
}
| |
This throws linker errors in GCC because 'func' can't be seen from main.cpp. Take out the inline keyword and it will compile, but in all likelyhood it will not be inlined.
Your link to parashift says nothing about when or where the compiler decides functions are to be inlined. It just shows some of the benefits and optimizations that can occur as a result.
tition:
Compilers are smart, but they're not magic. You generally shouldn't sweat the small stuff, and shouldn't try to "micro-optimize" code. However some basic concepts are good to know. Inlining is one of them. Don't let anyone talk you out of learning an important C++ concept.
EDIT:
To expand on that further... I think it's good to know about inlining. But even if you don't inline the function in this example, it won't matter -- there is a virtually 0% chance that this will lead to any kind of performance problem. So helios and PanGalactic are right in that you shouldn't really worry. I was just trying to show you something new.