1
这里是我的测试代码:thread_local和std :: future对象 - 对象的生命周期是什么?
vector<int> const & foo(int const counter)
{
thread_local static vector<int> v{counter, counter + 1, counter + 2};
return v;
}
int main()
{
using myFut = future<vector<int> const &>;
vector<myFut> futures;
for(int i{0}; i < 5; ++i)
{
futures.push_back(async(launch::async, &foo, i * 3));
}
for(myFut & fut : futures)
{
vector<int> v{fut.get()}; // or vector<int> const & v{fut.get()};
cout << v.size() << endl; // 0, I expect 3
}
return 0;
}
当foo()
返回一个线程可以被摧毁 - 用thread_local
变量在一起。但是由于我使用的是std::future
,变量的使用期限应该延长到拨打std::future::get()
,对吗?但在我的情况下,std::future
返回一个空向量。那么规则是什么?