Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
Tomilov Anatoliy Avatar asked Oct 18 '16 10:10

Tomilov Anatoliy


1 Answers

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.

like image 62
Columbo Avatar answered Sep 28 '22 10:09

Columbo