无法将智能指针移动到 std::function

Can't move a smart ptr into a std::function

我想创建一个 std::function 来捕获 auto_ptr/unique_ptr 但不能正确地做到这一点。我需要一个适用于 c++11 的解决方案,但我什至不知道如何在 c++14

上执行

以下示例适用于 c++11 (IncByTwenty) abd c++14 (IncByThirty)。但是,当我将那些 auto 更改为 Func 时,它不再编译。

typedef std::function<int( int )> Func;
Func IncByTen = std::bind( []( const int& p, int t ) -> int
{
    return p + t;  
}, 10, std::placeholders::_1 );

std::unique_ptr< int > pTwenty(new int(20));
// should have work in c++11 i think? cant assign to Func type
auto IncByTwenty = std::bind( []( const std::unique_ptr< int >& p, int t ) -> int
{
    return ( *p ) + t;  
}, std::move( pTwenty ), std::placeholders::_1 );

std::unique_ptr< int > pThirty = std::make_unique< int >( 30 );
// c++14  cant assign to Func type
auto IncByThirty  = [p{std::move(pThirty) }]( int t ) -> int
{
    return ( *p ) + t;  
};

std::cout << IncByTen(3) << " "  << IncByTwenty(4) << " " << IncByThirty(5);

我做错了吗?否则我需要创建一些可分配给 std::function 的东西,它需要使用移动运算符捕获一些局部变量。有什么建议吗?

由于std::function是可复制类型擦除容器,它只能包含可复制类型。

std::function documentation 声明它需要这个(F 是发送给构造函数的类型):

Type requirements

您的 lambda 必须可复制才能包含在 std::function

您可以使用 std::shared_ptr 代替或简单地使用非拥有指针:

auto pThirty = std::make_unique<int>(30);

auto IncByThirty = [p = pThirty.get()](int t) -> int {
    return *p + t;  
};

但是,您必须确保指向的数据与 lambda 和包含它的所有 std::function 一样长。

Can't move a [std::unique_ptr] into a std::function

不能,因为std::unique_ptr不可复制。 (否则它不可能是唯一的)。 std::function 要求函数对象是可复制的。

有人提议为不可复制的(特别是只能移动的)函数对象添加函数包装器:P0228rX,但这样的提议还不是语言的一部分。