英文:
Why does a non-void lambda which does not return a value compile?
问题
code snippet:
#include <iostream>
int main()
{
std::function<int(int)> func = [](int data)->int{
std::cout << "this is " << data << "\n";
};
func(3);
}
output
this is 3
我预期上面的代码不会编译通过,但令我惊讶的是它确实编译通过了。
编译器只生成了以下警告:
main.cpp:7:5: warning: non-void lambda does not return a value [-Wreturn-type]
};
^
1 warning generated.
我的问题是为什么没有生成编译错误?
<details>
<summary>英文:</summary>
code snippet:
#include <iostream>
int main()
{
std::function<int(int)> func = [](int data)->int{
std::cout << "this is " << data << "\n";
};
func(3);
}
output
this is 3
I expected the above not to compile at all, but to my supprise it did compile.
the compiler only generated this warning:
main.cpp:7:5: warning: non-void lambda does not return a value [-Wreturn-type]
};
^
1 warning generated.
My question is why wasnt a compile error generated?
</details>
# 答案1
**得分**: 3
> 我的问题是为什么没有生成编译错误?
在达到任何通常声明为非“void”返回类型的函数的结束“}”时,会导致_未定义行为_。编译器不必诊断这个问题,事实上通常无法这样做(因为这是一个不可决定的问题)。它通常也不能将其转化为错误而不是警告,因为它需要证明函数实际上是以有问题的执行路径被调用的。如果函数从未以达到结束“}”的方式调用,那么程序仍然具有明确定义的行为,而不是不符合规范的。
Lambda的主体实际上就是从Lambda生成的闭包类型的`operator()`成员函数的主体,同样的规则也适用于它。在Lambda表达式上声明的返回类型就是在这个`operator()`成员函数上声明的返回类型。
<details>
<summary>英文:</summary>
> My question is why wasnt a compile error generated?
Reaching the closing `}` of any usual function that is declared to have a non-`void` return type causes _undefined behavior_. The compiler does not have to diagnose this at all and in fact cannot generally do that (since it is an undecidable problem). It can't make it an error instead of a warning in general either, because it would need to prove that the function is actually called with the problematic execution path. If the function is never called in such a way that it will reach the closing `}`, then the program still has well-defined behavior and is not ill-formed.
The body of a lambda is nothing but the body of the `operator()` member function of the closure type generated from the lambda and the same rules apply to it. The return type declared on the lambda expression is the return type declared on this `operator()` member function.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论