简体   繁体   中英

Segmentation fault for lambda function in non-static data member initializer

I am unsure about a possible GCC bug in initialization of a std::function from a lambda function capturing this in a non-static data member initializer. Is this allowed by the C++ standard or is this UB?

Given the following code:

#include <functional>
#include <iostream>

template <typename T>
struct A {
      T x = 0;
      std::function<void(T)> f = [this](T v) { x = v; };
};

int main() {
      A<int> a;
      a.f(1);
      std::cout << a.x << "\n";
}

In my understanding, it should print 1 . However, when built with GCC 5.4.0 or GCC 6.2.0, af(1) emits a segmentation fault, because the captured this pointer is null.

The following alternatives work as I expected:

  • Using constructor initializer list:

     template <typename T> struct B { B() : f([this](T v) { x = v; }) {} T x = 0; std::function<void(T)> f; }; 
  • Without template:

     struct C { int x = 0; std::function<void(int)> f = [this](int v) { x = v; }; }; 

Also, when built with Clang 3.8.0, all three versions behave as I expect, which doesn't mean it is not UB.

You cannot do:

template <typename T>
struct A {
    T x = 0;
    std::function<void(T)> f = [this](T v) { x = v; };
};

As this does not exist when you define f . You need to initilize f in a constructor, such as:

A(){ f = [this](T v){ x=v; } }

It worked with G++4.8.

Your code compiles and runs on VS2015 (windows). So this is probably a compiler error.

Also, if you will remove the template it works on http://cpp.sh/ Try this code:

#include <functional>
#include <iostream>

struct A {
      int x = 0;
      std::function<void(int)> f = [this](int v) { x = v; };
};

int main() {
      A  a;
      a.f(1);
      std::cout << a.x << "\n";
}

running original code on cpp.sh gives:

 internal compiler error: in tsubst_copy, at cp/pt.c:12569
Please submit a full bug report

So I guess it's a bug

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM