【发布时间】:2020-01-31 19:41:11
【问题描述】:
我想创建一个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 的东西,并且它需要使用移动运算符捕获一些局部变量。有什么建议吗?
【问题讨论】:
-
不要在 C++11 中使用
std::auto_ptr。 -
我想完全用 c++11 来做例子。实际上我使用的是内部
uniqe_ptr实现 -
std::auto_ptr如何使示例完全使用 C++11? C++11 已被弃用。 -
啊,我很笨。编辑帖子。我把它和 make_unique 混淆了
-
@taytay 不用担心,有时人们会感到困惑,因为
std::make_unique只是添加到 C++14 中
标签: c++ c++11 c++14 smart-pointers