我编写了以下代码来调查一个内部捕获的地址 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);
}
当此代码运行时,&#34;典型输出&#34;看起来像:
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)按值i
和a
4)本地参数y
5)捕获的i
和a
但对我来说,很难理解地址的相对价值
捕获的i
相对于捕获的d
:它们似乎是,
如果我没有错,彼此之间只有两个字节。
这是什么意思? lambda范围内的i
和d
(以及a
)的地址是否重叠...?
提前感谢您的回答。
答案 0 :(得分:3)
因为 0x30 - 0x28 = 0x8 。
这是十六进制而不是十进制,所以数字序列应为
0x28 0x29 0x2a 0x2b 0x2c 0x2d 0x2e 0x2f 0x30 ...
如果是十进制数,那就是
28 29 30 ...
但这不是。
答案 1 :(得分:1)
但对于我来说,很难理解捕获的i的地址相对于捕获的d的相对值:它们似乎是,如果我没有错,除了每个之外只有两个字节其他
你错了,十六进制中的28和30是相隔8个字节 - 当你用十进制减去你借十(十进制的基数),十六进制你借16(十六进制的基数)所以16 - 8 == 8