catch
による再スローを除いて、データを受け取るブロックよりも長持ちさせたい場合は、例外オブジェクトからチェーンにデータをコピーする必要がありますthrow;
。(これには、たとえば、そのcatch
ブロックが。を介して終了する場合が含まれますthrow obj;
。)
これは、保存するデータをヒープに配置し、例外内のプライベートデータにswap
( C ++ 0xで)実装することで実行できます。move
もちろん、例外を除いてヒープを使用する場合は注意が必要です…しかし、最近のほとんどのOSでは、メモリのオーバーコミットによりnew
、良くも悪くも、スローが完全に防止されます。十分なメモリマージンと完全なメルトダウン時にチェーンから例外を削除することで、チェーンを安全に保つことができます。
struct exception_data { // abstract base class; may contain anything
virtual ~exception_data() {}
};
struct chained_exception : std::exception {
chained_exception( std::string const &s, exception_data *d = NULL )
: data(d), descr(s) {
try {
link = new chained_exception;
throw;
} catch ( chained_exception &prev ) {
swap( *link, prev );
} // catch std::bad_alloc somehow...
}
friend void swap( chained_exception &lhs, chained_exception &rhs ) {
std::swap( lhs.link, rhs.link );
std::swap( lhs.data, rhs.data );
swap( lhs.descr, rhs.descr );
}
virtual char const *what() const throw() { return descr.c_str(); }
virtual ~chained_exception() throw() {
if ( link && link->link ) delete link; // do not delete terminator
delete data;
}
chained_exception *link; // always on heap
exception_data *data; // always on heap
std::string descr; // keeps data on heap
private:
chained_exception() : link(), data() {}
friend int main();
};
void f() {
try {
throw chained_exception( "humbug!" );
} catch ( std::exception & ) {
try {
throw chained_exception( "bah" );
} catch ( chained_exception &e ) {
chained_exception *ep = &e;
for ( chained_exception *ep = &e; ep->link; ep = ep->link ) {
std::cerr << ep->what() << std::endl;
}
}
}
try {
throw chained_exception( "meh!" );
} catch ( chained_exception &e ) {
for ( chained_exception *ep = &e; ep->link; ep = ep->link ) {
std::cerr << ep->what() << std::endl;
}
}
}
int main() try {
throw chained_exception(); // create dummy end-of-chain
} catch( chained_exception & ) {
// body of main goes here
f();
}
出力(適切に不機嫌):
bah
humbug!
meh!