Why does this code snippet work?
#include <functional>
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> ptr(new int(666));
std::bind([](std::unique_ptr<int> &ptr){std::cout << *ptr << std::endl;}, std::move(ptr))();
}
You see the parameter of the lambda should be a lvalue-reference, whereas std::bind
pass a rvalue(i.e. std::move(ptr)
) to it.
Also, why does this code snippet not compile?
std::function<void()> = std::bind([](std::unique_ptr<int> &ptr){std::cout << *ptr << std::endl;}, std::move(ptr));
Just because std::function
need copy all the objects, whereas std::move(ptr)
is not copyable?
UPDATED:
The aforementioned code which could not compile is seen at https://localcoder.org/how-to-capture-a-unique-ptr-into-a-lambda-expression (i.e. see the 'solution 3' in the post). So the said solution is totally wrong. Am I right?