I have the following code:
#include <functional>
#include <memory>
#include <string>
#include <iostream>
struct A{
int i = 5;
};
class B{
std::unique_ptr<A> a;
std::function<void (void)> f;
public:
B(std::unique_ptr<A> a)
: a(std::move(a)),
f([&](){
std::cout << a->i << '\n'; //segfaults when executing a->i
})
{}
B()
: a(new A),
f([&](){
std::cout << a->i << '\n'; //works fine
})
{}
void execLambda(){
f();
}
void exec(){
std::cout << a->i << '\n'; //works fine
}
};
int main(){
B b1;
b1.exec(); //works fine
b1.execLambda(); //works fine
B b2(std::unique_ptr<A>(new A));
b2.exec(); //works fine
b2.execLambda(); //will segfault
return 0;
}
It seems when an object claims ownership of an existing unique_ptr and uses that unique_ptr in a lambda, a segmentation fault occurs. Why does a segmentation fault occur in this specific case? Is there anyway to use a unique_ptr in a lambda where ownership has been transferred?
Thank you very much!