c++ - 错误:无法从 '' 到 'std::tuple'
问题描述
在 godbolt.org 中编译我的代码时,我遇到以下错误:
In file included from <source>:5:
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread: In instantiation of 'std::thread::_State_impl<_Callable>::_State_impl(_Args&& ...) [with _Args = {void (Robot::*)(), Robot&}; _Callable = std::thread::_Invoker<std::tuple<void (Robot::*)(), Robot> >]':
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:226:20: required from 'static std::thread::_State_ptr std::thread::_S_make_state(_Args&& ...) [with _Callable = std::thread::_Invoker<std::tuple<void (Robot::*)(), Robot> >; _Args = {void (Robot::*)(), Robot&}; std::thread::_State_ptr = std::unique_ptr<std::thread::_State>]'
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:149:46: required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Robot::*)(); _Args = {Robot&}; <template-parameter-1-3> = void]'
<source>:154:51: required from here
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:211:46: error: could not convert '{std::forward<void (Robot::*)()>((* & __args#0)), std::forward<Robot&>((* & __args#1))}' from '<brace-enclosed initializer list>' to 'std::tuple<void (Robot::*)(), Robot>'
211 | : _M_func{{std::forward<_Args>(__args)...}}
| ^
| |
| <brace-enclosed initializer list>
Compiler returned: 1
看起来错误是在使用 std::thread 创建线程时出现的。代码的简化版本是:
class Robot {
private:
vector<double> position;
double area_covered;
mutex mtx;
public:
Robot(const vector<double> &initial_position) {
position = initial_position;
area_covered = 0.0;
}
void get_area() {
// ...
}
};
int main () {
vector<vector<double> > path{
{0.00359, -0.0013}, {0.00608, -0.00281}, {0.00756, -0.0027} };
Robot r3(path[0]);
std::thread thread1(&Robot::get_area, r3); // one thread
thread1.join();
}
解决方案
问题是r3
像这样传递给线程构造函数将尝试进行复制,并且Robot
不可复制也不可移动(因为std::mutex
)。
您可以通过指针传递对象:
std::thread thread1(&Robot::get_area, &r3);
或利用std::reference_wrapper
来自<functional>
:
std::thread thread1(&Robot::get_area, std::ref(r3));
推荐阅读
- python - Python向数据类型添加自定义函数
- java - 除非我清除缓存,否则 android 应用程序不会更新
- python - 在 discord.py 中完成后如何跳过或结束关键字命令?
- ssis-2017 - 加载到 SQL Server 表时如何防止 SSIS 截断文本字段
- javascript - 使用 Google App Scripts 删除重复行
- python - 检测 wxpython 中的拖动
- algorithm - Graph, Definition of strongly connected component (SCC)?
- python - 从 django 静态文件提供服务并上传到 heroku 时无法找到反应静态文件
- javascript - 如何从另一个可重用组件和容器组件访问可重用组件
- c++ - 是否可以将 QTreeWidgetItem 添加到 QTableWidgetItem?