What's the default calling convention of a C++ lambda function?

后端 未结 2 1221
自闭症患者
自闭症患者 2021-02-19 02:43

The following code was compiled with VC++ 2012:

void f1(void (__stdcall *)())
{}

void f2(void (__cdecl *)())
{}

void __cdecl h1()
{}

void __stdcall h2()
{}

i         


        
2条回答
  •  野的像风
    2021-02-19 03:28

    On VC++ 2012, compiler choose automatically calling conversion for stateless lambdas (that has no capture variables) when you convert "stateless lambda to function pointer".

    MSDN C++11 Features:

    Lambdas

    [...] Additionally in Visual C++ in Visual Studio 2012, stateless lambdas are convertible to function pointers. [...] (The Visual C++ in Visual Studio 2012 is even better than that, because we've made stateless lambdas convertible to function pointers that have arbitrary calling conventions. This is important when you are using APIs that expect things like __stdcall function pointers.)


    EDITED:

    NB: The calling conversion is out of C++ Standard, it depends on other specification such as platform ABI(application binary interface).

    The following answers are based on output assembly code with /FAs compiler option. So it's a mere guess, and please ask Microsoft for more detail ;P

    Q1. What's the calling convention of a C++ lambda function?

    Q3. If the calling convention is not defined, how to correctly recycle the stack space after having called a lambda function?

    First of all, C++ lambda(-expression) is NOT a function (nor function pointer), you can call operator() to lambda object like a calling normal function. And output assembly code says that VC++ 2012 generates lambda-body with __thiscall calling conversion.

    Q2. How to specify the calling convention of a C++ lambda function?

    AFAIK, there is no way. (It may be only __thiscall)

    Q4. Does the compiler automatically generate multiple versions of a lambda function? i.e. as the following pseudo-code: [...]

    Probably No. The VC++ 2012 lambda-type provides only one lambda-body implementation (void operator()()), but provides multiple "user-defined conversion to function pointer" for each calling conversion (operator return function pointer with void (__fastcall*)(void), void (__stdcall*)(void), and void (__cdecl*)(void) type).

    Here is an example;

    // input source code
    auto lm = [](){ /*lambda-body*/ };
    
    // reversed C++ code from VC++2012 output assembly code
    class lambda_UNIQUE_HASH {
      void __thiscall operator()() {
        /* lambda-body */
      }
      // user-defined conversions
      typedef void (__fastcall * fp_fastcall_t)();
      typedef void (__stdcall * fp_stdcall_t)();
      typedef void (__cdecl * fp_cdecl_t)();
      operator fp_fastcall_t() { ... }
      operator fp_stdcall_t() { ... }
      operator fp_cdecl_t() { ... }
    };
    lambda_UNIQUE_HASH lm;
    

提交回复
热议问题