Alexey Smirnoff
Alexey Smirnoff

Reputation: 31

How to correctly do the following: passing unique_ptr to lambda, then passing this lambda somewhere else

I have written this code, meaning that the lambda will own the unique pointer, but I also have to pass this lambda to other function to be called there.

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

using namespace std;

void call(function<void()>&& f) {
    f();
}

int main()
{
    auto ptr = make_unique<string>("hello\n");
    auto fn = [ptr = move(ptr)] () { cout << *ptr; };
    call(move(fn));
    return 0;
}

I got errors like

error: use of deleted function ‘main()::<lambda()>::<lambda>(const main()::<lambda()>&)’
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string<char>; _Dp = std::default_delete<std::__cxx11::basic_string<char> >]’

I'm looking for the way how to do what I need correctly.

Upvotes: 3

Views: 102

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38499

The closure, lambda is not a std::function<void()>, this is the issue. The compiler needs to create a temporary std::function<void()>. The working code

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

using namespace std;

void call(auto&& f) {
    f();
}

int main()
{
    auto ptr = make_unique<string>("hello\n");
    auto fn = [ptr = move(ptr)] () { cout << *ptr; };
    call(move(fn));
    return 0;
}

Upvotes: 4

Related Questions