c – std :: thread构造函数如何检测rvalue引用?
作者:互联网
显然,可以将rvalue引用传递给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
返回true.这意味着std :: decay< T> :: type将丢弃参数的rvalue引用部分.那么std :: thread构造函数如何知道lvalue或rvalue引用传递了哪个参数?因为所有的T&和T&&将通过std :: decay< T> :: type转换为T.
解决方法:
auto s = std::decay_copy(std::string("hello"));
相当于:
template<>
std::string std::decay_copy<std::string>(std::string&& src) {
return std::string(std::move(src));
}
std::string s = decay_copy<std::string>(std::string("hello"));
标签:perfect-forwarding,c,c11,multithreading,constructor 来源: https://codeday.me/bug/20191008/1873117.html