简体   繁体   English

传递捕获了unique_pointer的lambda

[英]pass a lambda that captures a unique_pointer

I'm using lambda generalized capture to move a unique_ptr into a lambda ( https://stackoverflow.com/a/16968463/118958 ). 我正在使用lambda广义捕获将unique_ptr移入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. 我想将此lambda传递给其他地方以设置回调函数,但是我不确定如何传递。

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? 关于如何执行上述操作的任何想法?

std::function must be both CopyConstructible and CopyAssignable, which means that it must be able to copy its target. std::function必须同时为CopyConstructible和CopyAssignable,这意味着它必须能够复制其目标。 Unfortunately, since your lambda is not copyable, you cannot store it in a std::function . 不幸的是,由于您的lambda不可复制,因此无法将其存储在std::function

You will have to resort to another implementation of callable type-erasure that works with movable-only objects. 您将不得不求助于可移动类型擦除的另一种实现,该实现与仅可移动对象一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM