为什么隐式“lambda到函数指针转换”禁止“通过引用”捕获静态成员? [英] Why does the implicit "lambda to function pointer conversion" forbid the "by reference" capture of static members?
问题描述
C ++ 11标准(或至少是我的版本,不是最后一个):
The C++11 standard says (or at least, the version I have - not the final one) :
类型为具有无lambda捕获的lambda表达式具有
公共非虚拟非显式const转换函数指针
到具有相同参数和返回类型的函数关闭
类型的函数调用操作符。
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator.
我理解为什么不能从有状态的lambda因为函数指针本身不能保存任何数据。
I understand why it is not possible to get a function pointer from a stateful lambda since a function pointer cannot hold any data by itself.
但是当捕获的对象只是静态成员/静态变量时,没有这样的限制,因为引用捕获的对象可以在函数本身中硬连线。
But when the captured objects are just a static members /static variable, there is no such limitation since the references to the captured objects can be hardwired in the function itself.
struct A {
static int count = 0;
void foo() {
static int bar = 0;
auto fun = [&]()->void {
count++;
bar++;
};
void(*ptrFun)();
ptrFun = fun; // forbidden by the quoted wording
}
};
为什么总是不可能将lambda转换为函数指针无国籍?
Why isn't it always possible to convert a lambda to a function pointer as soon as the former is stateless ? Am I missing something or does the committee forgot this specific point ?
推荐答案
A :: count
A::count
does not need to be captured at all. Only this
and local variables need to be captured. Variables with static storage duration (e.g., static data members, namespace-scope variables, or function-local static variables) do not need to be captured because they are "unique." There is exactly one instance of each such variable, so a reference to the object does not need to be captured.
如果从lambda中删除默认捕获(即,更改 [&]
到 []
)并定义 count
,它应该编译没有错误。 (我已经验证Visual C ++ 2012 RC和g ++ 4.5.1接受代码;唯一的变化,我要做的是移动内联初始化 count
,因为这些编译器都不支持C ++ 11的功能。)
If you remove the default capture from your lambda (i.e., change [&]
to []
) and define count
, it should compile without error. (I've verified that both Visual C++ 2012 RC and g++ 4.5.1 accept the code; the only change I had to make was to move the inline initialization of count
, since neither of those compilers supports that C++11 feature yet.)
这篇关于为什么隐式“lambda到函数指针转换”禁止“通过引用”捕获静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!