在尝试更好地理解C++ lambda的实现时,我让编译器将lambda视为一个对象,并且似乎它们在内存中的布局方式相同。
注意:这只是为了澄清问题,我不建议在生产环境中写这种类型的黑客代码。
这是语言规范保证的还是编译器实现的细节?
注意:这只是为了澄清问题,我不建议在生产环境中写这种类型的黑客代码。
这是语言规范保证的还是编译器实现的细节?
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
}
int[3]
对象做类似的事情。 - Caleth