I'm trying to std::bind
a std::move
on a std::unique_ptr
. The resulting function object seems to be immutable, so it would be impossible to perform the move when the functor is invoked.
I suspect this is because of the same reason why lambdas are immutable by default - invoking them should do the same thing every time. However there are cases where they need to be mutable, which is why we have the mutable
keyword.
void foo(std::unique_ptr<int>&& ptr)
{
cout << *ptr << endl;
}
int main()
{
std::unique_ptr<int> ptr = std::make_unique<int>(123);
std::bind(foo, std::move(ptr))(); // Doesn't compile
[&ptr]() { foo(std::move(ptr)); }(); // Equivalent, doesn't compile
[&ptr]() mutable { foo(std::move(ptr)); }(); // Compiles
return 0;
}
Instad of using bind
I could wrap a function call in a mutable lambda. However at least to me personally bind
looks much cleaner and simpler in this case.
I understand that invoking the mutable lambda twice would lead to undefined behavior, because I would be moving again from an already moved-from pointer. But in my case I know the functor will only be called once.
Is there a way I could use std::bind
to do this? Is there a bind_mutable
of sorts? If not, how should I go about writing it myself?
Aucun commentaire:
Enregistrer un commentaire