Return lambda function with motion capture

I have a function that builds a lambda function with motion capture (C ++ 1y only) and returns it.

#include <iostream>
#include <functional>
#include <memory>

using namespace std;

function<int ()> makeLambda(unique_ptr<int> ptr) {
    return [ ptr( move(ptr) ) ] () {
        return *ptr;
    };
}

int main() {
    // Works
    {
        unique_ptr<int> ptr( new int(10) );
        auto function1 = [ ptr(move(ptr)) ] {
            return *ptr;
        };
    }

    // Does not work
    {
        unique_ptr<int> ptr( new int(10) );
        auto function2 = makeLambda( std::move(ptr) );
    }

    return 0;
}

However, it appears that the copy constructor is called upon return unique_ptr<int>. Why is this / how can I get around this?

Link for insertion: http://coliru.stacked-crooked.com/a/b21c358db10c3933

+4
source share
1 answer

std::function<int ()> return, . , - std::unique_ptr. , std::function, , .

auto makeLambda(unique_ptr<int> ptr) {
    return [ ptr( move(ptr) ) ] () {
        return *ptr;
    };
}

, makeLambda unique_ptr<int>&&

+6

Source: https://habr.com/ru/post/1545769/


All Articles