开发者

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?


Well, it depends on your compiler. If it decides to inline, it will inline. If it decided not to, it won't inline. Inlining is controlled by compiler-specific heuristics. It depends on the compiler. It depends on the compiler settings. It depends on the context.

The only way to say for sure is to try and see what happens. "Typically", it should be inlined.

P.S. Keyword inline is redundant when the function is defined in class definition. Such functions are inline already. Adding the explicit inline keyword makes absolutely no difference.


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
    ; ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜