例外クラスと swap()
この組み合わせにふと考えを巡らせてみた。例外クラスにも swap() は必要か? でも、どうも明確な答えが見つからない。そもそも swap() って代入操作での例外安全性を保証するためだけのもの?
#include <iostream> #include <stdexcept> #include <string> class MyException: public std::exception { public: MyException(std::string const& msg) : msg_(msg) {} virtual ~MyException() throw() { } virtual const char* what() const throw() { return msg_.c_str(); } void swap(MyException& that) throw() { msg_.swap(that.msg_); } protected: std::string msg_; }; class DerivedException: public MyException { public: DerivedException(std::string const& msg) : MyException(msg) {} }; int main(int, char**) { try { try { throw DerivedException("mmm"); } catch (MyException& e) { MyException _e("test"); e.swap(_e); throw; } } catch (DerivedException& e) { std::cerr << e.what() << std::endl; } return 0; }
無理矢理 swap() を使ってみた。あまり感動はないなあ。