C++ 0x显示了一个使用示例std::forward:
template<class T>
void foo(T&& arg)
{
bar(std::forward<T>(arg));
}
Run Code Online (Sandbox Code Playgroud)
什么时候使用它std::forward总是有利的?
另外,它需要&&在参数声明中使用,它在所有情况下都有效吗?如果函数在其中声明,我认为你必须将临时函数传递给函数&&,那么可以使用任何参数调用foo吗?
最后,如果我有一个函数调用,如下所示:
template<int val, typename... Params>
void doSomething(Params... args) {
doSomethingElse<val, Params...>(args...);
}
Run Code Online (Sandbox Code Playgroud)
我应该用它代替:
template<int val, typename... Params>
void doSomething(Params&&... args) {
doSomethingElse<val, Params...>(std::forward<Params>(args)...);
}
Run Code Online (Sandbox Code Playgroud)
另外,如果在函数中使用两次参数,即同时转发到两个函数,是否明智使用std::forward?不会std::forward将相同的东西转换为临时两次,移动内存并使其无效以供第二次使用?以下代码是否可以:
template<int val, typename... Params>
void doSomething(Params&&... args) {
doSomethingElse<val, Params...>(std::forward<Params>(args)...);
doSomethingWeird<val, Params...>(std::forward<Params>(args)...);
}
Run Code Online (Sandbox Code Playgroud)
我有点困惑std::forward,我很乐意使用一些清理工作.
我只是在阅读Anthony Williams的行动书中的C++并发性.有这个经典的例子有两个线程,一个产生数据,另一个消耗数据,AW写的代码很清楚:
std::vector<int> data;
std::atomic<bool> data_ready(false);
void reader_thread()
{
while(!data_ready.load())
{
std::this_thread::sleep(std::milliseconds(1));
}
std::cout << "The answer=" << data[0] << "\n";
}
void writer_thread()
{
data.push_back(42);
data_ready = true;
}
Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么这个代码与我使用经典的挥发性bool而不是原子的不同.如果有人能够对这个问题敞开心扉,我将不胜感激.谢谢.
如何检查线程在C ++ 11及更高版本中是否已完成工作?我正在阅读文档,并编写了以下代码:
#include <iostream>
#include <thread>
void mythread()
{
//do some stuff
}
int main()
{
std::thread foo(mythread);
if (foo.joinable())
{
foo.join();
//do some next stuff
}
}
Run Code Online (Sandbox Code Playgroud)
joinable 仅告诉线程已开始工作,但我想知道如何编写代码以检查线程是否已完成工作。
例如:
#include <iostream>
#include <thread>
void mythread()
{
//do some stuff
}
int main()
{
std::thread foo(mythread);
if (foo.finishedWork())
{
foo.join();
//do some next stuff
}
}
Run Code Online (Sandbox Code Playgroud)