1

I am trying to completely understand what inline does but I get confused when it comes to constructors. So far I understood that inlining a function will put the function in the place it is called:

class X {
public:
     X() {}
     inline void Y() { std::cout << "hello" << std::endl; }
};
int main() {
     X x;
     x.Y; //so instead of this it will be: "std::cout << "hello" << std::endl;"
}

But what will this do (how does this get replaced?):

class X {
public:
     //or inline if the compilers feeling friendly for this example
     __forceinline X() {} 
}
Floris Velleman
  • 4,848
  • 4
  • 29
  • 46

1 Answers1

5

The meaning of inline is just to inform the compiler that the finction in question will be defined in this translation as well as possibly other translation units. The compiler uses this information for two purposes:

  1. It won't define the function in the translation unit as an externally visible, unique symbol, i.e., you won't get an error about the symbol being defined multiple times.
  2. It may change its view on whether it wants to call a function to access the finctionality or just expand the code where it is used. Whether it actually will inline the code will depend on what the compiler can inline, what it thinks may be reasonable to inline, and possibly on the phase of the moon.

There is no difference with respect to what sort of function is being inlined. That is, whether it is a constructor, a member function, a normal function, etc.

BTW, member functions defined inside the class definition are implicitly declared inline. There is no need to mention it explicitly. __forecedinline seems to be a compiler extension and assuming it does what it says is probably a bad idea as compilers are a lot better at deciding on what should be inlined than humans.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380