Trouble move-capturing std::unique_ptr in a lambda using std::bind

Posted by user2478832 on Stack Overflow See other posts from Stack Overflow or by user2478832
Published on 2013-06-24T14:55:02Z Indexed on 2013/06/24 16:21 UTC
Read the original article Hit count: 485

Filed under:
|
|
|

I'd like to capture a variable of type std::vector<std::unique_ptr<MyClass>> in a lambda expression (in other words, "capture by move"). I found a solution which uses std::bind to capture unique_ptr (http://stackoverflow.com/a/12744730/2478832) and decided to use it as a starting point. However, the most simplified version of the proposed code I could get doesn't compile (lots of template mistakes, it seems to try to call unique_ptr's copy constructor).

#include <functional>
#include <memory>

std::function<void ()> a(std::unique_ptr<int>&& param)
{
    return std::bind( [] (int* p) {},
        std::move(param));
}

int main()
{
    a(std::unique_ptr<int>(new int()));
}

Can anybody point out what is wrong with this code?

EDIT: tried changing the lambda to take a reference to unique_ptr, it still doesn't compile.

#include <functional>
#include <memory>

std::function<void ()> a(std::unique_ptr<int>&& param)
{
    return std::bind( [] (std::unique_ptr<int>& p) {}, // also as a const reference
        std::move(param));
}

int main()
{
    a(std::unique_ptr<int>(new int()));
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++11