2013-05-02 130 views

回答

6

一個std::packaged_task有一個關聯的std::future對象,它將保存異常(或任務的結果)。您可以通過撥打std::packaged_taskget_future()成員函數來檢索未來。

這意味着它足以讓throw與打包任務關聯的函數內發生異常,以便任務未來捕獲該異常(並在未來對象上調用get()時重新拋出異常)。

例如:

#include <thread> 
#include <future> 
#include <iostream> 

int main() 
{ 
    std::packaged_task<void()> pt([]() { 
     std::cout << "Hello, "; 
     throw 42; // <== Just throw an exception... 
    }); 

    // Retrieve the associated future... 
    auto f = pt.get_future(); 

    // Start the task (here, in a separate thread) 
    std::thread t(std::move(pt)); 

    try 
    { 
     // This will throw the exception originally thrown inside the 
     // packaged task's function... 
     f.get(); 
    } 
    catch (int e) 
    { 
     // ...and here we have that exception 
     std::cout << e; 
    } 

    t.join(); 
} 
相關問題