显然可以将右值引用传递给 std::thread
构造函数。我的问题是这个构造函数在 cppreference 中的定义.它说这个构造函数:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
Creates new std::thread object and associates it with a thread of execution. First the constructor copies/moves all arguments (both the function object f and all args...) to thread-accessible storage as if by the function:
template <class T>
typename decay<T>::type decay_copy(T&& v) {
return std::forward<T>(v);
}
据我所知:
std::is_same<int, std::decay<int&&>::type>::value
返回真值。这意味着 std::decay<T>::type
将删除参数的右值引用部分。那怎么办std::thread
构造函数知道哪个参数是由左值或右值引用传递的?因为所有 T&
和 T&&
将转换为 T
通过 std::decay<T>::type
最佳答案
std::thread
构造函数知道其参数的值类别,因为它知道 Function
和 Args...
是什么,它用于将其参数完美地转发到 decay_copy
(或等效项)。
实际的线程函数并不知道值的类别。它总是作为右值调用,带有所有右值参数 - 这是有道理的:f
和 args...
的拷贝是线程本地的,不会在其他任何地方使用。
关于c++ - std::thread 构造函数如何检测右值引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37242552/