public member function
<future>

std::promise::set_exception

void set_exception (exception_ptr p);
設定異常
將異常指標 p 儲存在“就緒”的共享狀態中。

如果與同一共享狀態關聯的 future 物件當前正在等待 future::get 呼叫,則解除阻塞並丟擲由 p 指向的異常物件。

引數

p
一個 exception_ptr 物件。
exception_ptr 是一個用於引用異常物件的智慧指標型別。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// promise::set_exception
#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception

void get_int (std::promise<int>& prom) {
  int x;
  std::cout << "Please, enter an integer value: ";
  std::cin.exceptions (std::ios::failbit);   // throw on failbit
  try {
    std::cin >> x;                           // sets failbit if input is not int
    prom.set_value(x);
  }
  catch (std::exception&) {
    prom.set_exception(std::current_exception());
  }
}

void print_int (std::future<int>& fut) {
  try {
    int x = fut.get();
    std::cout << "value: " << x << '\n';
  }
  catch (std::exception& e) {
    std::cout << "[exception caught: " << e.what() << "]\n";
  }
}

int main ()
{
  std::promise<int> prom;
  std::future<int> fut = prom.get_future();

  std::thread th1 (print_int, std::ref(fut));
  std::thread th2 (get_int, std::ref(prom));

  th1.join();
  th2.join();
  return 0;
}

可能的輸出

Please enter an integer value: boogey!
[exception caught: ios_base::failbit caught]


資料競爭

promise 物件被修改。
共享狀態被修改為原子操作(不會導致資料競爭)。

異常安全

基本保證:如果丟擲異常,則 promise 物件處於有效狀態。

此成員函式在以下條件下丟擲異常
異常型別錯誤條件描述
future_errorfuture_errc::no_state該物件沒有共享狀態(它已被移動賦值
future_errorfuture_errc::promise_already_satisfied共享狀態已儲存值或異常
根據庫實現的不同,此成員函式還可能丟擲異常來報告其他情況。

另見