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
fstream
objects and lambdas in afor
loop, and for eachfstream
there is one lambda writing to it. So the access to thefstream
objects 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?
const_cast
, instead mark your lambda asmutable
.const_cast
is UB. You can't modify objects that were casted this way. The correct way to do this, as Rakete1111 pointed out, is to mark the objectmutable
const
; it is only the generatedoperator()
that is markedconst
. Casting awayconst
from aconst
lvalue to a non-const
object to modify said object is completely fine - and the entire point ofconst_cast
. Sure, it's not good style here, I don't think, but it's not UB. Or if it is, why?operator()
that is notconst
-qualified and hence provides read-write access to the capture members of the lambda.