"std::thread"对象中构造函数中的"decay_copy"做什么



我试图理解std::thread的构造函数,但无法理解如何表示/处理参数类型。根据cpprreference判断,一个简化的构造函数可以如下所示:

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);
}

根据我的分析,x1x2都是在内部std::forward之后的左值引用类型,而X{}是右值引用类型。我认为我们需要以某种方式将x1x2分离,以便通过值或引用传递它。分析引出了三个问题:

  • 以上分析正确吗
  • decay_copy如何正确解开类型
  • 在开始这件事一段时间后,我想知道:哦,麻烦,为什么这件事这么复杂?这能更容易些吗?答案当然是否定的,但我对整个操作仍然缺乏直觉

感谢您的任何提示、建议或解释!

Std线程将参数类型复制(或移动(到一个衰退版本中。衰减的版本既不是引用,也不是常量,也不是volatile,也不是数组(数组和函数变成指针(。

如果您想要一个左值引用参数,请使用引用包装器。否则,线程ctor中被调用的函数将获得一个右值;decay副本只是确定线程函数中传递的右值是如何根据std线程参数构造的。

最新更新