无法将智能指针移至std :: function

问题描述 投票:0回答:2

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

以下示例适用于c ++ 11(IncByTwenty)和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的对象,并且需要使用move运算符捕获一些局部变量。有什么建议吗?

c++ c++11 c++14 smart-pointers
2个回答
0
投票

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

std::function documentation声明需要此(std::function是发送给构造函数的类型:]

类型要求

您的lambda必须可复制才能包含在Allocator

您可以改用std::function或简单地使用非所有权指针:

std::shared_ptr

但是,您必须确保指向的数据与lambda以及包含它的所有auto pThirty = std::make_unique<int>(30); auto IncByThirty = [p = pThirty.get()](int t) -> int { return *p + t; }; 一样长。


0
投票

无法将[std::function]移到std::unique_ptr

您不能,因为std::function不可复制。 std::unique_ptr是不可复制的(否则不能唯一)。

[有人建议为不可复制的(特别是仅移动的)函数对象添加函数包装:std::unique_ptr,但此类提议尚不属于语言的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.