1. 程式人生 > 其它 >reference to non static member function must be called

reference to non static member function must be called

編譯器會給類的非靜態成員函式新增一個this引數。

int square(int num) {
    return num * num;
}

class Hehe{
    public:
    int square(int num) {
        return num * num;
    }
};

int main() {
    int a = square(2);
    Hehe h;
    int b = h.square(3);
    return 0;
}

006t.gimple

int square (int num)
{
  int D.2396;

  D.2396 = num * num;
  return D.2396;
}


int main ()
{
  int D.2398;

  {
    int a;
    struct Hehe h;
    int b;

    try
      {
        a = square (2);
        b = Hehe::square (&h, 3);
        D.2398 = 0;
        return D.2398;
      }
    finally
      {
        h = {CLOBBER};
      }
  }
  D.2398 = 0;
  return D.2398;
}


int Hehe::square (struct Hehe * const this, int num)
{
  int D.2401;

  D.2401 = num * num;
  return D.2401;
}


x86-64 gcc 11.1

square(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], edi
        mov     eax, DWORD PTR [rbp-4]
        imul    eax, eax
        pop     rbp
        ret
Hehe::square(int):
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     DWORD PTR [rbp-12], esi
        mov     eax, DWORD PTR [rbp-12]
        imul    eax, eax
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     edi, 2
        call    square(int)
        mov     DWORD PTR [rbp-4], eax
        lea     rax, [rbp-9]
        mov     esi, 3
        mov     rdi, rax
        call    Hehe::square(int)
        mov     DWORD PTR [rbp-8], eax
        mov     eax, 0
        leave
        ret

https://stackoverflow.com/questions/28746744/passing-capturing-lambda-as-function-pointer