Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Do function wrappers work with inline?

If you've enabled full optimizations in your compiler and have classes setup like this:

class A
{
    void Do_A_Stuff();
};
class B
{
    A a;
    void Do_B_Stuff() { a.Do_A_Stuff(); }
};
class C
{
    B b;
    void Do_C_Stuff() { b.Do_B_Stuff(); }
};
class D
{
    C c;
    void Do_D_Stuff() { c.Do_C_Stuff(); }
};

Is there ever a situation where calling Do_D_Stuff() would be slower than directly calling Do_A_Stuff()? Also, would this require the inline keyword on each wrapper 'chain' or, since it is only a suggestion, could the compiler decide to optimize this without the keyword?

I realize there is a lot of information about inlining available, but I could not find any information specifically about chaining many wrappers together.

like image 831
Jonathan Avatar asked Mar 28 '13 23:03

Jonathan


1 Answers

Also, would this require the inline keyword on each wrapper 'chain' or, since it is only a suggestion, could the compiler decide to optimize this without the keyword?

Yes, the compiler could decide to optimize it anyway, and it could also decide not to optimize it even if you specified the inline keyword (possibly producing a warning if the appropriate compiler options are set) - notice, that member functions defined in a class definition are implicitly marked as inline.

In general, if inlining is possible, the compiler will decide whether to inline or not based on the body of the function being called. However, inlining may not be possible at all if the function is a virtual function, or if the definition of the function is not visible to the compiler.

Provided that the conditions for inlining are satisfied and that the compiler considers it appropriate, there is no technical problem in inlining over a chain of function calls.

As a minor remark, notice that the functions in your classes should be public, otherwise they won't be accessible to your wrappers.

like image 183
Andy Prowl Avatar answered Sep 20 '22 20:09

Andy Prowl