1

I'm using lambda generalized capture to move a unique_ptr into a lambda (https://stackoverflow.com/a/16968463/118958). I want to pass this lambda elsewhere to set a callback function, but I'm not sure how.

Here's a small example with what I'm trying to do that fails to compile:

void set_callback(std::function<void(void)> cb);
void move_callback(std::function<void(void)> &&cb);

void test() {
    auto a_ptr = std::make_unique<int>(10);
    auto lambda = [a_ptr = std::move(a_ptr)] () {};

    // set_callback(lambda);            // I understand why this wouldn't work
    move_callback(std::move(lambda));   // but I would expect this to be OK
}

Any idea on how to do something like the above?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
ynimous
  • 4,642
  • 6
  • 27
  • 43

1 Answers1

4

std::function must be both CopyConstructible and CopyAssignable, which means that it must be able to copy its target. Unfortunately, since your lambda is not copyable, you cannot store it in a std::function.

You will have to resort to another implementation of callable type-erasure that works with movable-only objects.

Quentin
  • 62,093
  • 7
  • 131
  • 191