2016-05-15 80 views
2

显然,可以将右值引用传递给std::thread构造函数。我的问题是在cppreference中定义这个构造函数。它说,这种构造:std :: thread构造函数如何检测右值引用?

template< class Function, class... Args > 
explicit thread(Function&& f, Args&&... args); 

创建新的std :: thread对象,并将其与 执行线程关联。首先,构造拷贝/移动所有参数(这两个 函数对象f和所有ARGS ...),以线程访问的存储仿佛 由函数:

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会删除参数的右参考部分。那么std::thread构造函数如何知道哪个参数是由左值或右值引用传递的?因为所有T&T&&std::decay<T>::type转换为T

+0

”将值左值,数组指向和函数指针隐式转换应用于类型T,删除cv限定符,并将结果类型定义为成员typedef类型“http:// en.cppreference.com/w/cpp/types/decay - 你在哪里看到它会删除引用? – xaxxon

+0

@xaxxon你缺少':: type'。 –

+0

@ T.C。删除 - 但为什么他们是一样的? – xaxxon

回答

2
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")); 
+0

就是那个C++?....我从来没有见过函数名在< – xaxxon

+0

@xaxxon中或多或少地声明。它试图展示模板扩展的结果。 –

1

这是一个完美的转发通病。如果你想恢复函数中有关右值的信息,你必须使用std :: forward std::forward。如果你对值类型检测感兴趣,你可以阅读这个value_category。从描述中你可以找到编译器在编译时如何识别右值,左值,右值,左值和右值的信息。

3

std::thread构造函数知道它的参数的值类,因为它知道什么FunctionArgs...是,它使用完美向前它的参数decay_copy(或同等学历)。

实际的线程函数不知道值类别。它总是作为右值与所有右值参数一起调用 - 这是有道理的:fargs...的副本对于线程是本地的,并且不会在其他任何地方使用。 “

相关问题