Lambda捕获的对std :: cout的本地引用而无需询问 [英] Local reference to std::cout captured by lambda without asking for it
问题描述
我迷失了方向吗?总是允许这样做吗?
Have I lost my mind? Was this always permitted?
#include <iostream>
int main()
{
auto& os = std::cout;
auto write = []()
{
os << "what\n";
};
write();
}
我正在使用:
Apple LLVM版本10.0.0(clang-1000.10.44.4)
目标:x86_64-apple-darwin17.7.0
Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin17.7.0
尽管在Coliru上也可以看到
Though also see on Coliru:
我一直认为空捕获不会捕获任何东西.
I always thought an empty capture would not capture anything.
事实上,MSDN 说:
一个空的捕获子句[],表示lambda表达式的主体在封闭范围内不访问任何变量.
An empty capture clause, [ ], indicates that the body of the lambda expression accesses no variables in the enclosing scope.
进一步的研究表明,这实际上可以捕获const
的东西(我也不知道,但是无论如何),但是os
不是const
(没有参考!尽管它是是不可变…).
Further research suggests that this is in fact okay for capturing const
things (which I also didn't know, but whatever), but os
is not const
(no reference is! though it is immutable…).
我在打开-Wextra
时发现了这一点,并注意到Clang认为&os
捕获(在我的真实代码中)是不必要的.删除它后,我错失了找到该构建的工作机会.
I came across this when turning on -Wextra
and noticing that Clang thought a &os
capture (which is present in my real code) was unnecessary. Removing it I was staggered to find the build worked.
推荐答案
有一个开放的 clang report 涵盖了lambda表达式隐式捕获引用的情况,这不仅限于std::cout
,还包括被发现引用常量表达式的reference变量.
There's an open clang report that cover the case of implicit capture of references by lambda expressions, this is not limited to std::cout
but to references variable that are found to refer to constant expressions.
有关更多参考,CWG上的后备缺陷报告为 CWG-1472
For more reference, the backing defect report on the CWG is CWG-1472
基于@ Rakete1111的评论,我应该明确指出clang正确地接受了代码, 这是应用上述CWG缺陷的结果.由于以下原因,该报告被重新打开 诊断位置不是因为他们对接受的理解是错误的
Based on @Rakete1111 comment, I should have pointed out explicitly that clang is right in accepting the code, which is the result of applying the CWG defect mentioned above. The report was reopened because of diagnosis location not because they were wrong about the acceptance
这篇关于Lambda捕获的对std :: cout的本地引用而无需询问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!