std::future<T>::get
來自 cppreference.com
主模板 |
||
T get(); |
(1) | (C++11 起) |
std::future<T&> 特化 |
||
T& get(); |
(2) | (C++11 起) |
std::future<void> 特化 |
||
void get(); |
(3) | (C++11 起) |
get
成員函式等待(透過呼叫 wait())直到共享狀態就緒,然後檢索儲存在共享狀態中的值(如果有)。呼叫此函式後,valid() 為 false。
如果在呼叫此函式之前 valid() 為 false,則行為未定義。
目錄 |
[編輯] 返回值
1) 儲存在共享狀態中的值 v,作為 std::move(v)。
2) 作為值儲存在共享狀態中的引用。
3) (無)
[編輯] 異常
如果異常儲存在 future 引用的共享狀態中(例如透過呼叫 std::promise::set_exception()),則會丟擲該異常。
[編輯] 注意
C++ 標準建議實現檢測在呼叫之前 valid() 為 false 的情況,並丟擲具有錯誤條件 std::future_errc::no_state 的 std::future_error。
[編輯] 示例
執行此程式碼
#include <chrono> #include <future> #include <iostream> #include <string> #include <thread> std::string time() { static auto start = std::chrono::steady_clock::now(); std::chrono::duration<double> d = std::chrono::steady_clock::now() - start; return "[" + std::to_string(d.count()) + "s]"; } int main() { using namespace std::chrono_literals; { std::cout << time() << " launching thread\n"; std::future<int> f = std::async(std::launch::async, [] { std::this_thread::sleep_for(1s); return 7; }); std::cout << time() << " waiting for the future, f.valid() = " << f.valid() << '\n'; int n = f.get(); std::cout << time() << " f.get() returned " << n << ", f.valid() = " << f.valid() << '\n'; } { std::cout << time() << " launching thread\n"; std::future<int> f = std::async(std::launch::async, [] { std::this_thread::sleep_for(1s); return true ? throw std::runtime_error("7") : 7; }); std::cout << time() << " waiting for the future, f.valid() = " << f.valid() << '\n'; try { int n = f.get(); std::cout << time() << " f.get() returned " << n << ", f.valid() = " << f.valid() << '\n'; } catch (const std::exception& e) { std::cout << time() << " caught exception " << e.what() << ", f.valid() = " << f.valid() << '\n'; } } }
可能的輸出
[0.000004s] launching thread [0.000461s] waiting for the future, f.valid() = 1 [1.001156s] f.get() returned with 7, f.valid() = 0 [1.001192s] launching thread [1.001275s] waiting for the future, f.valid() = 1 [2.002356s] caught exception 7, f.valid() = 0
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2096 | C++11 | 過載 (1) 需要檢查 T 是否是 可移動賦值 |
未要求 |
[編輯] 另請參閱
檢查 future 是否具有共享狀態 (公共成員函式) |