型情報を保持したまま例外を保存する -> 別スレッドで再度投げる
C++0xを扱ってるサイトとかを読んでれば、1年とか前からやってる人はまぁいたでしょう内容ですが、興味深いと思うのでとりあえず・・・
#include <iostream> #include <exception> #include <thread> #include <mutex> #include <condition_variable> using namespace std; auto main( void ) -> int { mutex _sync_mutex; condition_variable _sync_cond; exception_ptr expr = nullptr; thread th( [&] { unique_lock< mutex > lk( _sync_mutex ); _sync_cond.wait( lk, [&]{ return expr != nullptr; } ); try { rethrow_exception( expr ); } catch ( const exception &e ) { cout << e.what() << endl; } } ); try { throw exception(); } catch ( ... ) { unique_lock< mutex > lk( _sync_mutex ); expr = current_exception(); _sync_cond.notify_one(); } th.join(); return 0; }
いまは単にstd::exception()を投げてますが、例外に組み込み型を使っても型情報は保存されます。(組み込み型を投げるとかふざけてますが)
あと、自分で作ったstd::exceptionを継承してないものとか、std::exceptionからの派生だけど、その途中でポリモーフィックな型でないものになってしまってたりして、std::exception&に渡すことのできなくなったものも、std::exception_ptrを使うと保存できます。
C++0xは面白いですね。いろいろできて。
あと、std::threadってgccのビルド時に使ったスレッディングライブラリが必要?自分の環境だと-lpthreadが必要だけど、ビルドしたときに別のライブラリで組むとまたそれが必要?