In C++20, [*this]
was allowed. So I tried following code:
class A
{
public:
int x = 5;
function<int(int)>fun = [*this](int y) mutable
{
return x;
};
};
int main() {
int x;
A a{};
cout<<a.fun(3)<<endl;
cout<<a.x<<endl;
return 0;
}
I tried to capture [*this]
in class but got segmentation fault; however, the following methods are possible.
class A
{
int x = 5;
function<int(int)>fun = [this](int y)
{
return this->x + y;
};
};
class A
{
int x = 5;
function<int(int)>fun = [=](int y)
{
return this->x + y;
};
};
class A
{
int x = 5;
function<int(int)>fun = [&](int y)
{
return this->x + y;
};
};
Can someone explain this for me?
You're making a copy of an unitialized std::function
object.
When an A
object is constructed, it needs to make a copy of itself for the lambda that will be used to initialize fun
to capture. That copy needs to copy fun
, but fun
hasn't been initialized yet, and so attempting to make a copy of it results in undefined behavior.
Your other examples are fine, because none of them make a copy of *this
, and therefore never try to copy its uninitialized fun
member.