在 C++0x lambda 中通过复制捕获引用变量

Capturing reference variable by copy in C++0x lambda(在 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 中通过复制捕获引用变量

基础教程推荐