c++templatesoptimizationinline

Is this call to a function object inlined?


In the following code, Foo::add calls a function via a function object:

struct Plus {
  inline int operator()(int x, int y) const {
    return x + y;
  }
};

template<class Fct>
struct Foo {
  Fct fct;
  Foo(Fct f) : fct(f) {}
  inline int add(int x, int y) {
    return fct(x,y); // same efficiency adding directly?
  }  
};

Is this the same efficiency as calling x+y directly in Foo::add? In other words, does the compiler typically directly replace fct(x,y) with the actual call, inlining the code, when compiling with optimizations enabled?


Solution

  • For g++ 4.4.1, it will inline at -O1 or above.

    I used the program (as well as your code):

    int main()
    {
        Foo<Plus> foo((Plus()));
        int a, b;
        cin >> a >> b;
        int x = foo.add(a, b);
        cout << x << endl;
    }
    

    For -O0, you get (g++ -S, excerpted):

    main:
    .LFB960:
            ; ...
        call    _ZN3FooI4PlusEC1ES0_
        ; ...
        call    _ZN3FooI4PlusE3addEii
        ; ...
    
    _ZN3FooI4PlusE3addEii:
            ; ...
        call    _ZNK4PlusclEii
            ; ...
    
    ZNK4PlusclEii:
        ; ...
        ; This is the actual add
        leal    (%edx,%eax), %eax
        ; ...
    

    At -O1 or -O2, Foo and Plus disappear entirely from this test.

    main:
        ; ...
        addl    24(%esp), %eax
        ; ...