jak*_*kar 32 c++ lambda gcc g++ c++11
根据此问题的答案和注释,当通过值捕获引用变量时,lambda对象应该复制引用的对象,而不是引用本身.但是,海湾合作委员会似乎并没有这样做.
使用以下测试:
#include <stddef.h>
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char** argv)
{
int i = 10;
int& ir = i;
[=]
{
cout << "value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
[&]
{
cout << "reference capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
使用GCC 4.5.1进行编译,使用-std=c++0x和运行会给出以下输出:
value capture
i: 10
ir: -226727748
&i: 0x7ffff27c68a0
&ir: 0x7ffff27c68a4
reference capture
i: 10
ir: 10
&i: 0x7ffff27c68bc
&ir: 0x7ffff27c68bc
Run Code Online (Sandbox Code Playgroud)
通过复制捕获时,ir只引用垃圾数据.但它i通过引用捕获时正确引用.
这是GCC中的错误吗?如果是这样,有人知道后来的版本是否修复了它?什么是正确的行为?
如果第一个lambda函数更改为
[i, ir]
{
cout << "explicit value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
Run Code Online (Sandbox Code Playgroud)
然后输出看起来正确:
explicit value capture
i: 10
ir: 10
&i: 0x7fff0a5b5790
&ir: 0x7fff0a5b5794
Run Code Online (Sandbox Code Playgroud)
这看起来越来越像一个bug.
| 归档时间: |
|
| 查看次数: |
8210 次 |
| 最近记录: |