C++ can compilers inline a function pointer?

后端 未结 4 1727
难免孤独
难免孤独 2020-12-02 18:31

Suppose I\'ve got a function functionProxy that takes a generic parameter function and call its operator():

template&l         


        
4条回答
  •  隐瞒了意图╮
    2020-12-02 19:17

    Have tried the following templated pointer-to-lambda code:

    volatile static int a = 0;
    
    template  class Widget {
       public: 
          Widget(const Lambda* const lambda) : lambda_(lambda) { }
          void f() { (*lambda_)(); }
       private:
          const Lambda* const lambda_;
    };
    
    int main() {
       auto lambda = [](){ a++; };
       Widget widget(&lambda);
       widget.f();
    }
    

    GNU g++ 4.9.2, Intel icpc 16.0.1, and clang++ 3.5.0 all inlined both widget.f() and (*lambda_)() calls using -O2. That is, a was incremented directly inside main() according to disassembled binaries.

    Inlining was applied even with non-const lambda and lambda_ pointers (removing both const).

    Ditto with a local variable and lambda capture:

    int main() {
       volatile int a = 0;
       auto lambda = [&a](){ a++; };
       ...
    

提交回复
热议问题