c++ - std::thread 构造函数如何检测右值引用?

标签 c++ multithreading c++11 constructor perfect-forwarding

显然可以将右值引用传递给 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 构造函数知道其参数的值类别,因为它知道 FunctionArgs... 是什么,它用于将其参数完美地转发到 decay_copy(或等效项)。

实际的线程函数并不知道值的类别。它总是作为右值调用,带有所有右值参数 - 这是有道理的:fargs... 的拷贝是线程本地的,不会在其他任何地方使用。

关于c++ - std::thread 构造函数如何检测右值引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37242552/

相关文章:

c++ - 使用宏 _BIND_TO_CURRENT_VCLIBS_VERSION 是否有任何副作用?

c++ - PostMessage无法在Winform应用程序中与分配的控制台一起使用

c++ - 可以向任何方向延伸的对象的二维网格 C++

c++ - boost 分配器无法在递归上下文中编译

c++ - 为什么使用 union、class 和 lambda 会产生段错误?

c++ - C++ 中的数组初始化(非字符串)

ios - 什么可能导致此代码不允许重新进入跳板?

multithreading - Perl 解释器线程的替代方案是什么?

python - 如何运行并行线程以在视频流的每一帧上应用函数?

具有右值参数调用的 C++11 模板函数