Capturing reference variable by copy in C++0x lambda(在 C++0x lambda 中通过复制捕获引用变量)
问题描述
根据this question的回答和评论,当引用变量被值捕获时,lambda对象应该制作被引用对象的副本,而不是引用本身.但是,GCC 似乎没有这样做.
According to the answers and comments for this question, when a reference variable is captured by value, the lambda object should make a copy of the referenced object, not the reference itself. However, GCC doesn't seem to do this.
使用以下测试:
#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;
}
使用 GCC 4.5.1 编译,使用 -std=c++0x
,然后运行会得到以下输出:
Compiling with GCC 4.5.1, using -std=c++0x
, and running gives the following output:
value capture
i: 10
ir: -226727748
&i: 0x7ffff27c68a0
&ir: 0x7ffff27c68a4
reference capture
i: 10
ir: 10
&i: 0x7ffff27c68bc
&ir: 0x7ffff27c68bc
当被复制时,ir
只是引用垃圾数据.但是当通过引用捕获时,它正确地引用了 i
.
When captured by copy, ir
just references junk data. But it correctly references i
when captured by reference.
这是 GCC 中的错误吗?如果是这样,有人知道以后的版本是否会修复它吗?正确的行为是什么?
Is this a bug in GCC? If so, does anyone know if a later version fixes it? What is the correct behavior?
如果第一个lambda函数改为
If the first lambda function is changed to
[i, ir]
{
cout << "explicit value capture" << endl
<< "i: " << i << endl
<< "ir: " << ir << endl
<< "&i: " << &i << endl
<< "&ir: " << &ir << endl
<< endl;
}();
那么输出看起来是正确的:
then the output looks correct:
explicit value capture
i: 10
ir: 10
&i: 0x7fff0a5b5790
&ir: 0x7fff0a5b5794
这看起来越来越像一个错误.
This looks more and more like a bug.
推荐答案
这个问题刚刚在 gcc-4.7 主干和 gcc-4.6 分支中修复.这些应该在 gcc-4.7.0(从现在开始 - 仍处于第 1 阶段)和 gcc-4.6.2(唉 4.6.1 刚刚问世.)中可用.
This has just been fixed in gcc-4.7 trunk and gcc-4.6 branch. These should be available in gcc-4.7.0 (a while from now - still in stage 1) and gcc-4.6.2 (alas 4.6.1 just came out.)
但无畏者可以等待下一个快照或获得颠覆副本.
But the intrepid could wait for the next snapshots or get a subversion copy.
有关详细信息,请参阅审计跟踪.
See audit trail for details.
这篇关于在 C++0x lambda 中通过复制捕获引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++0x lambda 中通过复制捕获引用变量
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01