地址确实在C lambda表达式中具有捕获
What addresses do have captures in a C++ lambda expression?
我编写了以下代码,以调查在捕获中的地址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)值i
和a
4)本地参数y
5)捕获的i
和a
,但对我来说,很难理解地址的相对价值相对于捕获的d
捕获的i
:它们似乎是如果我没有错,只有两个字节彼此相距。
这是什么意思?lambda范围内的i
和d
(以及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
相关文章:
- 这 4 个 lambda 表达式之间有什么区别?
- 使用成员在类中创建 lambda 表达式
- 使用自动推导的 lambda 参数作为常量表达式
- 将 lambda 表达式传递给 std::function in C++
- 在 lambda 表达式中使用 std::atomic
- 不是 lambda 函数中的常量表达式
- &&对lambda表达式有什么好处?
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 列表.erase 中的 lambda 表达式
- 使用 lambda 表达式的 Raspbian G++ 8.3.0 导致 ']' 之前的预期主表达式 - 即使标准设置为 c++14
- 仅通过引用捕获的 lambda 表达式是否保证不会抛出?
- C++: priority_queue:模板参数中的 lambda 表达式
- 容器如何处理 lambda 表达式的参数
- 在C++ Lambda 表达式中,为什么人们更喜欢按值捕获而不是作为参数传递?
- 如何在 lambda 表达式中传递变量?
- 针对 std::function 的 lambda 表达式和模板推导:为什么会这样?
- 如何修改Lambda表达式以将输出放入文本文件
- C++如何使用lambda表达式来捕获上一次迭代的值
- 为什么Qt在信号和插槽中为lambda表达式抛出错误?
- C++:从捕获函数参数的函数返回 lambda 表达式