这是一个例子:
#include<iostream>
#include<thread>
using namespace std;
void f1(double& ret) {
ret=5.;
}
void f2(double* ret) {
*ret=5.;
}
int main() {
double ret=0.;
thread t1(f1, ret);
t1.join();
cout << "ret=" << ret << endl;
thread t2(f2, &ret);
t2.join();
cout << "ret=" << ret << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
ret=0
ret=5
Run Code Online (Sandbox Code Playgroud)
用gcc 4.5.2编译,有和没有-O2标志.
这是预期的行为吗?
这个节目数据是否免费比赛?
谢谢
我使用新的c ++ 11 std::thread接口遇到了问题.
我无法弄清楚如何std::ostream将对a的引用传递给线程将执行的函数.
这是传递整数的示例(在gcc 4.6下按预期编译和工作):
void foo(int &i) {
/** do something with i **/
std::cout << i << std::endl;
}
int k = 10;
std::thread t(foo, k);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试传递一个ostream时,它无法编译:
void foo(std::ostream &os) {
/** do something with os **/
os << "This should be printed to os" << std::endl;
}
std::thread t(foo, std::cout);
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点,还是根本不可能?
注意:从编译错误看来它似乎来自一个已删除的构造函数...
我正在学习如何获得type重载函数test()vs 的返回值test(double)。
我从SO答案(由chris)修改了代码。
#include <type_traits>
#include <utility>
int test();
double test(double x);
template<typename... Ts>
using TestType = decltype(test(std::declval<Ts>()...))(Ts...);
int main() {
std::result_of< TestType<double> >::type n = 0;
//^ ### compile error ###
using doubleDat = std::result_of< TestType<double> >::type ;
doubleDat n=0;
}
Run Code Online (Sandbox Code Playgroud)
我遇到了编译错误。
错误:“ std :: result_of”中没有名为“ type”的类型
我认为:-
TestType<...>是“可变模板”。
用我自己的话说,它就像一个带有任何参数的压缩缩写。
该TestType<double>是ID的的test(double)功能。
std::result_of<TestType<double>>::type是的返回类型test(double)。doubleDat应该是double。问题: …