Why does lambda init-capture not work for unique_ptr?

后端 未结 1 616
野性不改
野性不改 2020-12-11 03:59

I\'m trying to use the C++14 init-capture feature to move a unique_ptr inside a lambda via capture. For some reason, both gcc and clang refuse to compile my code, insisting

相关标签:
1条回答
  • 2020-12-11 04:15

    Because std::function must be copyable:

    std::function satisfies the requirements of CopyConstructible and CopyAssignable.

    And the constructor in question:

    Initializes the target with a copy of f.

    The lambda that you are constructing (completely validly) has a unique_ptr member, which makes it noncopyable. If you rewrote runFunc to take an arbitrary functor by value:

    template <typename F>
    void runFunc(F f) {
        auto ff = std::move(f);
        ff();
    }
    

    it would compile.

    0 讨论(0)
提交回复
热议问题