简短的例子:
#include <iostream>
int main()
{
int n;
[&](){n = 10;}(); // OK
[=]() mutable {n = 20;}(); // OK
// [=](){n = 10;}(); // Error: a by-value capture cannot be modified in a non-mutable lambda
std::cout << n << "\n"; // "10"
}
Run Code Online (Sandbox Code Playgroud)
问题:为什么我们需要mutable关键字?它与传统参数传递给命名函数有很大不同.背后的理由是什么?
我的印象是,按值捕获的整个点是允许用户更改临时值 - 否则我几乎总是更好地使用按引用捕获,不是吗?
有什么启示吗?
(顺便说一句,我使用的是MSVC2010.这应该是标准的AFAIK)
使用win32线程,我有直接向前GetExitCodeThread()提供线程函数返回的值.我正在寻找类似的东西std::thread(或提升线程)
据我所知,这可以通过期货完成,但究竟如何呢?
我怎样才能或者可以将模板函数传递给异步?
这是代码:
//main.cpp
#include <future>
#include <vector>
#include <iostream>
#include <numeric>
int
main
()
{
std::vector<double> v(16,1);
auto r0 = std::async(std::launch::async,std::accumulate,v.begin(),v.end(),double(0.0));
std::cout << r0.get() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是错误消息:
^
a.cpp:13:88: note: candidates are:
In file included from a.cpp:1:0:
/usr/include/c++/4.8/future:1523:5: note: template std::future::type> std::async(std::launch, _Fn&&, _Args&& ...)
async(launch __policy, _Fn&& __fn, _Args&&... __args)
^
/usr/include/c++/4.8/future:1523:5: note: template argument deduction/substitution failed:
a.cpp:13:88: note: couldn't deduce template parameter ‘_Fn’
auto r0 = std::async(std::launch::async,std::accumulate,v.begin(),v.end(),double(0.0));
^
In file included from a.cpp:1:0:
/usr/include/c++/4.8/future:1543:5: note: …