gpt4 book ai didi

c++ - C++ Lambda 的内存布局

转载 作者:太空狗 更新时间:2023-10-29 23:35:01 25 4
gpt4 key购买 nike

为了更好地理解 C++ lambda 的实现,我欺骗了编译器将 lambda 视为一个对象,而且它们在内存中的布局似乎相同。

注意:这只是为了澄清,我不提倡在生产中编写这些类型的 hack

这是由语言规范或编译器实现细节保证的吗?

struct F
{
int a; int b; int c;
void printLambdaMembers()
{
cout << this << endl; // presumably the lambda 'this'
cout << a << endl; // prints 5
cout << b << endl;
cout << c << endl;
}
};

void demo()
{
int a = 5;
int b = 6;
int c = 7;
auto lambda = [a,b,c]() { cout << "In lambda!\n"; };
// hard cast the object member function pointer to the lambda function
void(decltype(lambda)::*pf)() const = (void(decltype(lambda)::*)() const) (&F::printLambdaMembers);
// run the member function on the lambda pointer
(lambda.*pf)(); // we get 5,6,7

}

最佳答案

该标准不要求 lambda 闭包具有特定的布局。参见 [expr.prim.lambda.closure] :

The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.

...

The closure type is not an aggregate type. An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

  • the size and/or alignment of the closure type,
  • whether the closure type is trivially copyable, or
  • whether the closure type is a standard-layout class.

An implementation shall not add members of rvalue reference type to the closure type.


但是,为了符合平台 ABI 并使目标文件可互操作,编译器可能必须以完全相同的方式布局和命名 mangle lambda 对象。

关于c++ - C++ Lambda 的内存布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50739828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com