A positive lambda: #39;+[]{}#39; - What sorcery is this?(一个积极的 lambda: +[]{} - 这是什么魔法?)
问题描述
In Stack Overflow question Redefining lambdas not allowed in C++11, why?, a small program was given that does not compile:
int main() {
auto test = []{};
test = []{};
}
The question was answered and all seemed fine. Then came Johannes Schaub and made an interesting observation:
If you put a
+
before the first lambda, it magically starts to work.
So I'm curious: Why does the following work?
int main() {
auto test = +[]{}; // Note the unary operator + before the lambda
test = []{};
}
It compiles fine with both GCC 4.7+ and Clang 3.2+. Is the code standard conforming?
Yes, the code is standard conforming. The +
triggers a conversion to a plain old function pointer for the lambda.
What happens is this:
The compiler sees the first lambda ([]{}
) and generates a closure object according to §5.1.2. As the lambda is a non-capturing lambda, the following applies:
5.1.2 Lambda expressions [expr.prim.lambda]
6 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. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
This is important as the unary operator +
has a set of built-in overloads, specifically this one:
13.6 Built-in operators [over.built]
8 For every type
T
there exist candidate operator functions of the form
T* operator+(T*);
And with this, it's quite clear what happens: When operator +
is applied to the closure object, the set of overloaded built-in candidates contains a conversion-to-any-pointer and the closure type contains exactly one candidate: The conversion to the function pointer of the lambda.
The type of test
in auto test = +[]{};
is therefore deduced to void(*)()
. Now the second line is easy: For the second lambda/closure object, an assignment to the function pointer triggers the same conversion as in the first line. Even though the second lambda has a different closure type, the resulting function pointer is, of course, compatible and can be assigned.
这篇关于一个积极的 lambda: '+[]{}' - 这是什么魔法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:一个积极的 lambda: '+[]{}' - 这是什么魔法?
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01