std::future<T>::get
提供: cppreference.com
T get(); |
(1) | (汎用 future テンプレートのみのメンバ)(C++11以上) |
T& get(); |
(2) | (future<T&> テンプレート特殊化のみのメンバ)(C++11以上) |
void get(); |
(3) | (future<void> テンプレート特殊化のみのメンバ)(C++11以上) |
get 関数は future が有効な結果を持つまで待機し、(どのテンプレートが使用されたかによって) それを取得します。 結果の待機のために実質的に wait() を呼びます。
汎用テンプレートと2つのテンプレート特殊化はそれぞれ get のいずれかのバージョンを持ちます。 3つのバージョンの get は戻り値の型が異なるだけです。
この関数を呼ぶ前に valid() が false であった場合、動作は未定義です。
共有状態は解放されます。 この関数を呼んだ後、 valid() は false になります。
引数
(なし)
戻り値
1)
std::move(v) としての、共有状態に格納されている値 v。2) 共有状態に値として格納されている参照。
3) なし。
例外
フューチャーが参照している共有状態に例外が格納されていた場合 (例えば std::promise::set_exception() の呼び出しを通して)、その例外が投げられます。
ノート
処理系は呼び出し前に valid() が false であったときにそれを検出し、エラーコンディション std::future_errc::no_state を持つ std::future_error を投げることが推奨されます。
例
Run this code
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <chrono>
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() << " future.get() returned with " << 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() << " future.get() returned with " << 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] future.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
関連項目
| フューチャーが共有状態を持っているかどうか調べます (パブリックメンバ関数) |