我想创建将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运算符捕获一些局部变量。有什么建议吗?
由于std::function
是可复制类型的擦除容器,因此它只能包含可复制类型。
std::function
documentation声明需要此(std::function
是发送给构造函数的类型:]
类型要求
- [
F
必须满足F
和Callable的要求。- CopyConstructible必须满足
Alloc
的要求。
您的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;
};
一样长。
无法将[
std::function
]移到std::unique_ptr
您不能,因为std::function
不可复制。 std::unique_ptr
是不可复制的(否则不能唯一)。
[有人建议为不可复制的(特别是仅移动的)函数对象添加函数包装:std::unique_ptr
,但此类提议尚不属于语言的一部分。