Orient Orient - 1 year ago 142
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
from trunk, but for
from trunk fails with error message (link):

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

Definition of
in namespace scope works fine for both.

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

Which compiler is right?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download