c++ - 将只移动函数参数传递给 boost::thread 构造函数
问题描述
以下适用于std::thread
. 它打印 10 作为输出,这是我想要的。
void foo(std::unique_ptr<int> && in) {
std::cout << *in;
}
int main(){
auto in = std::make_unique<int>(10);
std::thread t(foo, std::move(in));
t.join();
}
但是,使用 Boost 1.72 的类似尝试无法编译
void foo(std::unique_ptr<int> && in) {
std::cout << *in;
}
int main(){
auto in = std::make_unique<int>(10);
boost::thread t(foo, std::move(in));
t.join();
}
Error : note: copy constructor of 'list1<boost::_bi::value<std::unique_ptr<int>>>' is implicitly deleted because base class 'storage1<boost::_bi::value<std::unique_ptr<int>>>' has a deleted copy constructor template< class A1 > class list1: private storage1< A1 >
我觉得这很令人惊讶,因为 boost::thread 的文档说明了以下内容:
带参数的线程构造函数模板 <class F,class A1,class A2,...> thread(F f,A1 a1,A2 a2,...);
前提条件:F 和每个 An 必须是可复制的或可移动的。
由于我传递了 astd::unique_ptr
作为论点,因此我满足了“可移动”标准。所以,我想知道为什么 boost 线程要构建std::unique_ptr
? 它不应该将 std::unique_ptr 移动到线程对象中,然后像实现那样将其进一步移动到线程函数std::thread
中吗?
解决方案
根据文档,boost::thread
以完全相同的方式使用参数boost::bind
,并且函数和参数的这种组合不适合boost::bind
(并且std::bind
就此而言)。
std::bind(foo, std::move(in))(); // error
boost::bind(foo, std::move(in))(); // error
std::thread
比std::bind
或更健壮boost::bind
。
如果您需要将参数移动到foo
,则需要将其包装在一个函数或 lambda 中,该函数或 lambda 通过非常量左值引用接受它并将其移动到foo
. 否则,只需更改foo
为接受非常量左值引用参数。
推荐阅读
- react-native - 如何要求用户接受自签名证书?网络视图
- javascript - 没有订阅者时如何暂停 shareReplay
- swift - 如何连续发射子弹
- php - DateTime 用 PHP 解析日期
- c# - 错误 RZ3007:目标标记名称不能为空或空格。Razor 在发布时抛出错误,但在本地工作
- javascript - 我们如何在 shopify 的 settings_schema.json 中设置 min 和 max 属性
- solr - Solr 节点在完全索引后挂在恢复状态 - solr 写入限制
- vue.js - 从 main.js 文件或 index.html 调用 service worker 是否正确?
- swift - 如何在导航栏的普通和大标题上使用不同的样式?
- excel - 在 Excel 中创建带有属性的外部文档列表