posts - 9, comments - 0, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
Depending on the precise conditions under which such pairs of simultaneously active exceptions arise, program execution either terminates or yields undefined behavior. In this example, it yields undefined behavior.
C++ does not like destructors that emit exceptions!
#include <iostream>
#include <vector>
struct Exception
{
    Exception(){std::cout << "Exception Constructor" << std::endl;}
    ~Exception(){std::cout << "Exception Destructor" << std::endl;}
};
class Widget {
public:
  ~Widget() {std::cout << "Widget Destructor" << std::endl; throw Exception();
  }        //this might emit an exception
  void print(){std::cout << "print" << std::endl;}
};
                
void doSomething();
int main()
{
    doSomething();
}
void doSomething()
{
  std::vector<Widget> v;
  v.push_back(Widget());
  v.push_back(Widget());
  v.push_back(Widget());
  v.push_back(Widget());
  std::vector<Widget>::iterator it = v.begin();
  while(it != v.end())
  {
    std::cout << "end" << std::endl;
    (*it).print();
    it++;
  }
}
complie with g++
[shangtang@BTSOM-1 study]$ ./a.out
Widget Destructor
Exception Constructor
terminate called after throwing an instance of 'Exception'
Aborted (core dumped)
There are two primary ways to avoid the trouble.

   1, Terminate the program if catch a exception, typically by calling std::abort (cstdlib)
  2, 
Swallow the exception if catch a exception, print a log

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理