Orient Orient - 1 month ago 17
C++ Question

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);
}


Works fine for
clang++
from trunk, but for
g++
from trunk fails with error message (link):


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


Definition of
point_of_cone
in namespace scope works fine for both.

Slightly modified definition with
[this]
lambda capture works fine also for both in either global or local scope.

Which compiler is right?

Answer

That's a gcc bug.

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

This fails, but if we…

  • change & to this, or
  • declare A as having namespace scope,

it works. Neither of these should have any effect on the well-formedness, though.

Reported: #78019.