地址确实在C lambda表达式中具有捕获

What addresses do have captures in a C++ lambda expression?

本文关键字:表达式 lambda 地址      更新时间:2023-10-16

我编写了以下代码,以调查在捕获中的地址lambda表达

 # include <iostream>
 # include <functional>
 using fu = std::function<void(int)>;
 void f(fu l, int x)
  { l(x); }
 int main()
  {
   double d{1.17};
   int i = 12;
   char a = 'a';
   // write addresses on stdout:
   std::cout << "address of d in main is " << &d << std::endl;
   std::cout << "address of i in main is " << &i << std::endl;
   std::cout << "address of a in main is 0x" 
             << std::hex << reinterpret_cast<long>(&a) << std::dec 
             << std::endl;
   // now let us introduce a lambda expr as follows
   auto l = [&, i, a](int y)
    {
     std::cout<<"captured d by reference " << d
              <<" at address " << &d << std::endl;
     std::cout<<"captured i by value " << i
              <<" at address " << &i << std::endl;
     std::cout<<"captured a by value " << a
              <<" at address 0x" << std::hex
              << reinterpret_cast<long>(&a) << std::dec
              << std::endl;
     std::cout<<"got parameter " << y
              <<" at address " << &y << std::endl;
    };
  // now send the lambda to f which will execute it
  f(l, i);
  }

运行此代码时,"典型输出"看起来像:

   address of d in main is 0x7ffd96bc4628
   address of i in main is 0x7ffd96bc4624
   address of a in main is 0x7ffd96bc4623
   captured d by reference 1.17 at address 0x7ffd96bc4628
   captured i by value 12 at address 0x7ffd96bc4630
   captured a by value a at address 0x7ffd96bc4634
   got parameter 12 at address 0x7ffd96bc4564

在该输出中,我可以轻松理解:

1)main中的地址的相对值

2)通过参考d捕获的地址的身份

3)值ia

捕获的不同地址

4)本地参数y

的完全不同的地址

5)捕获的ia

的地址的相对值

,但对我来说,很难理解地址的相对价值相对于捕获的d捕获的i:它们似乎是如果我没有错,只有两个字节彼此相距。

这是什么意思?lambda范围内的id(以及a)的地址重叠...?

预先感谢您的任何答案。

因为 0x30-0x28 = 0x8

这是十六进制,而不是DEC,因此数字序列应为

0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f 0x30 ...

如果是十进制数,那将是

28 29 30 ...

,但不是。

,但对我来说,很难理解被捕获的i相对于被捕获的D的相对价值:如果我没有错,它们似乎只有两个字节,彼此之间只有两个字节。

您错了,十六进制中的28和30分别是8个字节 - 当您在十进制中减去借用10(十进制的基部)时,在十六进制中,您借用16(十六进制的基础),所以16-8 == 8