未记录的GCC c++ 11扩展?在lambda捕获列表中捕获任意表达式

Undocumented GCC C++11 extension? Capturing arbitrary expressions in lambda capture lists

本文关键字:lambda 列表 表达式 任意 记录 GCC c++ 扩展      更新时间:2023-10-16

奇怪的是,GCC 4.7.2似乎对以下代码没有问题:

template<typename T>
T&& identity(T&& x1) {
    return std::forward<T>(x1);
}
int main(int, char**) {
    int x1 = 1;
    int &x2 = identity(x1);
    auto f = [&x1]() mutable {
        x1 = x1 + 1;
    };
    auto g1 = [y=x2+1]() {
        static_assert(std::is_same<decltype(y), const int>::value, "fail");
        std::cout << "g1: " << y << std::endl;
    };
    auto h1 = [y=identity(x1)+1]() {
        static_assert(std::is_same<decltype(y), const int>::value, "fail");
        std::cout << "h1: " << y << std::endl;
    };
    auto g2 = [&y=x2]() {
        static_assert(std::is_same<decltype(y), int&>::value, "fail");
        std::cout << "g2: " << y << std::endl;
    };
    auto h2 = [&y=identity(x1)]() {
        static_assert(std::is_same<decltype(y), int&>::value, "fail");
        std::cout << "h2: " << y << std::endl;
    };
    f(); g1(); h1(); g2(); h2();
    f(); g1(); h1(); g2(); h2();
    return 0;
}

结果如下:

g1: 2
h1: 2
g2: 2
h2: 2
g1: 2
h1: 2
g2: 3
h2: 3

我似乎找不到任何关于在lambda捕获列表中捕获任意表达式的提及,即使在n3285(日期为2012-10-02)中也是如此。而且,我似乎找不到任何关于这个作为官方GCC扩展的文档。

这是一个未记录的GCC扩展(一个VLAs作为结构成员,一个GCC已经提前实现的提议/即将到来的c++特性,两者都没有,还是什么?

正如评论中所指出的,该特性与最近的一个提案大致相似,但它在最初的标准化之前很久就实现了。在标准开发过程中,GCC充当了一个原型,最初反映了作者喜欢的任何想法,后来对其进行了改进。一些为了保持标准的合理简单而不得不被删减的想法正以提案的形式重新引入。lambda有很大的成长空间。

现在,这只是另一个bug。它从未从最初的实现中删除,因为还没有人报告它。


更新:这是c++ 14以来的标准特性