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
返回一個空向量。那麼規則是什麼?