[英]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. 我不确定在一个lambda函数初始化std::function
可能存在GCC错误,该函数在非静态数据成员初始值设定项中捕获this
。 Is this allowed by the C++ standard or is this UB? 这是允许的C ++标准还是这个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
. 根据我的理解,它应该打印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. 但是,当使用GCC 5.4.0或GCC 6.2.0构建时, af(1)
会发出分段错误,因为捕获的this
指针为空。
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. 此外,当使用Clang 3.8.0构建时,所有三个版本都按照我的预期运行,这并不意味着它不是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
. 由于this
,当你定义不存在f
。 You need to initilize f
in a constructor, such as: 您需要在构造函数中初始化f
,例如:
A(){ f = [this](T v){ x=v; } }
It worked with G++4.8. 它适用于G ++ 4.8。
Your code compiles and runs on VS2015 (windows). 您的代码在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: 此外,如果您将删除它在http://cpp.sh/上工作的模板,请尝试以下代码:
#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: 在cpp.sh上运行原始代码给出:
internal compiler error: in tsubst_copy, at cp/pt.c:12569
Please submit a full bug report
So I guess it's a bug 所以我猜这是一个错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.