在默认初始化器 gcc vs clang 中使用 lambda

Using lambda in default initializer gcc vs clang

#include <cassert>
#include <cmath>

int main()
{
    struct point_of_cone
    {
        double x, y;
        double z = [&] { using std::sqrt; return sqrt(x * x + y * y); }();
    };
    point_of_cone p = {3.0, 4.0};
    assert(p.z == 5.0);
}

对于来自中继的 clang++ 工作正常,但是对于来自中继的 g++ 工作失败并显示错误消息 (link):

error: 'this' was not captured for this lambda function

命名空间范围内 point_of_cone 的定义对两者都适用。

使用 [this] lambda 捕获略微修改的定义在全局或本地范围内都可以正常工作。

哪个编译器是正确的?

这是一个 gcc 错误。

int main() {
    struct A {
        int x, i = [&] { return x; }();
    } a{0};
}

这失败了,但是如果我们……

  • &更改为this,或
  • 声明 A 具有命名空间范围,

有效。不过,这些都不应该对格式良好有任何影响。

报告:#78019