我试图理解 std::thread
的构造函数,但无法理解参数类型是如何表示/处理的。从cppreference来看,一个简化的构造函数可以绘制如下:
class thread {
public:
template <class Function, class Arg>
thread(Function&& f, Arg&& arg) {
// something happening
std::invoke(decay_copy(std::forward<Function>(f)),
decay_copy(std::forward<Arg>(arg)));
// something else happening
}
};
cppreference 将 decay_copy
定义为:
template <class T>
std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }
我尝试了以下示例:
struct X{};
int main() {
X x1{};
X& x2 = x1;
auto f = []() { return; };
thread t1{f, x1}; // arg should be of type X& after the inner std::forward<Arg>(arg);
thread t2{f, x2}; // arg should be of type X& after the inner std::forward<Arg>(arg);
thread t3{f, X{}}; // arg should be of type X&& after the inner std::forward<Arg>(arg);
}
根据我的分析,x1
和x2
在内部std::forward
whileX之后都是左值引用类型{}
是右值引用类型。我相信我们需要以某种方式分离 x1
和 x2
来按值或按引用传递它。通过分析,我提出了三个问题:
- 以上分析正确吗?
decay_copy
如何正确理清类型?- 开始这样做一段时间后,我想知道:哦,麻烦了,为什么这件事如此复杂?可以做得更容易吗?答案当然是否定的,但我对整个操作仍然缺乏直觉。
我非常感谢任何提示、建议或解释!
最佳答案
Std 线程将拷贝(或移动)到参数类型的衰退版本中。腐烂的版本不是引用,也不是常量,也不是 volatile ,也不是数组(数组和函数变成指针)。
如果您需要左值引用参数,请使用引用包装器。否则,线程构造函数中被调用的函数将获得右值;衰减复制只是确定如何从 std 线程参数构造您在线程函数中传递的右值。
关于c++ - `decay_copy` 对象的构造函数中的 `std::thread` 有何作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67947814/