Zero Lee的专栏

Life scope of one object example

Example code:
 1 class A {
 2 public:
 3     A(int i) {
 4         if (i!=1) {
 5             std::vector<int> a;
 6             a.at(0= 1;
 7         } else
 8             std::cout << "ctor ok." << std::endl;
 9     }
10     ~A() {
11         std::cout << "A:dtor." << std::endl;
12     }
13 };
14 
15 void f()
16 {
17     try {
18         A a(1);
19         a.~A();
20         new (&a) A(2);  /* here, throw one exception, but still destroy a again  */
21     } catch() {
22         std::cout << "catch exception." << std::endl;
23     }
24 }
25 

Above code snippet, if in placement new call, constructor of one class throws one exception, that a will still be destroyed again, since a is one automatic object, according to Cpp standard. In this case, one object constructed once, but destroyed twice, undefined/unpredicated behavior may happen.


posted on 2010-12-03 14:48 Zero Lee 阅读(204) 评论(0)  编辑 收藏 引用 所属分类: CC++ Programming


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