Question

Is the following free function implicitly inlined in C++, similar to how member functions are implicitly inlined if defined in the class definition?

void func() { ... }

Do template functions behave the same way?

Was it helpful?

Solution

No, it's not implicitly inlined. The compiler has no way of knowing if another module will use this function, so it has to generate code for it.

This means, for instance, that if you define the function like that in a header and include the header twice, you will get linker errors about multiple definitions. Explicit inline fixes that.

Of course, the compiler may still inline the function if it thinks that will be efficient, but it's not the same as an explicit inlining.

Template functions are implicitly inlined in the sense that they don't require an inline to prevent multiple definition errors. I don't think the compiler is forced to inline those either, but I'm not sure.

OTHER TIPS

It depends what you mean by inlined. A compiler can optimise any function by placing its emitted code inline at the call site. However, if you mean does the code you ask about behave as if it was declared:

inline void func() { ... }

then the answer is no. If you place your code in two different compilation units and build the executable, you will get multiple definition errors. If you explicitly mark the function as "inline", you will not.

Regarding template functions, then some part of the compilation system will see to it that multiple instantiations of the same template do not cause multiple definition errors.

It might be inlined, depending on if the compiler decides to make it inline or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top