Search code examples
c++classinline

What does compiler really do when a class inline function is called?


None static member functions implicitly have the this pointer. So these inline functions will not be replaced by compiler when they are called outside the class, am I right? This seems that usage of class inline functions is very restrictive!


Solution

  • An optimizing compiler can inline as it wishes.

    For example, you might compile and link an entire program with g++ -flto -O2 (link-time whole program optimization option of GCC...).

    (caveat: using g++ -flto -O2 would slow down significantly your build process; basically everything is compiled nearly "twice", once at "compile" time, once at "link" time, where GIMPLE representation gets re-optimized)

    You'll be surprised by what function calls get inlined (a lot of them could be). It is unrelated to static or not functions marked or not as inline.

    So you should not care about inlining (it is an implementation and optimization detail), but you hope that the compiler will do a good job.

    (sometimes with g++ you want to disable most inlining to ease debugging with gdb; then compile with g++ -fno-inline -Wall -Wextra -O0 -g)

    So these inline functions will not be replaced by compiler when they are called outside the class, am I right?

    You are wrong, this is just an implicit argument (see also that), and of course compilers are often inlining calls to member functions. In practice C++ would be inefficient if compilers did not that optimization (since many member functions -e.g. getters and setters- are quite short and quick).

    Remember that C++ is a specification written in some report (it is not a compiler). Inlining is a quality of implementation issue, and may or not happen.

    If you care about what do the compiler really does (and you should not care, but you need to avoid undefined behavior in your code), ask it to show the generated assembler code. With GCC compile with g++ -O2 -fverbose-asm -S to get a foo.s assembler file from a foo.cc translation unit.