![](/img/trans.png)
[英]Is it allowed to call a non-static member function in a default member initializer?
[英]Segmentation fault for lambda function in non-static data member initializer
我不确定在一个lambda函数初始化std::function
可能存在GCC错误,该函数在非静态数据成员初始值设定项中捕获this
。 这是允许的C ++标准还是这个UB?
给出以下代码:
#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";
}
根据我的理解,它应该打印1
。 但是,当使用GCC 5.4.0或GCC 6.2.0构建时, af(1)
会发出分段错误,因为捕获的this
指针为空。
以下备选方案按预期工作:
使用构造函数初始化列表:
template <typename T> struct B { B() : f([this](T v) { x = v; }) {} T x = 0; std::function<void(T)> f; };
没有模板:
struct C { int x = 0; std::function<void(int)> f = [this](int v) { x = v; }; };
此外,当使用Clang 3.8.0构建时,所有三个版本都按照我的预期运行,这并不意味着它不是UB。
你做不到:
template <typename T>
struct A {
T x = 0;
std::function<void(T)> f = [this](T v) { x = v; };
};
由于this
,当你定义不存在f
。 您需要在构造函数中初始化f
,例如:
A(){ f = [this](T v){ x=v; } }
它适用于G ++ 4.8。
您的代码在VS2015(windows)上编译并运行。 所以这可能是一个编译器错误。
此外,如果您将删除它在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";
}
在cpp.sh上运行原始代码给出:
internal compiler error: in tsubst_copy, at cp/pt.c:12569
Please submit a full bug report
所以我猜这是一个错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.