I recently struggled with a bug hard to find for me. I tried to pass a lambda to a function taking a std::function object. The lambda was capturing a noncopyable object.
I figured out, obviously some copy must happen in between all the passings. I came to this result because I always ended in an error: use of deleted function error.
Here is the code which produces this error:
void call_func(std::function<void()> func)
{
func();
}
int main()
{
std::fstream fs{"test.txt", std::fstream::out};
auto lam = [fs = std::move(fs)] { const_cast<std::fstream&>(fs).close(); };
call_func(lam);
return 0;
}
I solved this by capseling the std::fstream object in an std::shared_ptr object. This is working fine, but I think there may be a more sexy way to do this.
I have two questions now:
- Why is this error raising up?
- My idea: I generate many
fstreamobjects and lambdas in aforloop, and for eachfstreamthere is one lambda writing to it. So the access to thefstreamobjects is only done by the lambdas. I want do this for some callback logic. Is there a more pretty way to this with lambdas like I tried?