比思論壇

標題: 一段程序的分析——C++析构器,何时析构 [打印本頁]

作者: 妖刀路过    時間: 2014-7-18 20:47
標題: 一段程序的分析——C++析构器,何时析构
[url=][/url]
1 #include <iostream> 2 #include <string> 3 4 class Pet 5 { 6 public: 7     Pet(std::string theName); 8     ~Pet(); 9 10     static int getCount();11 12 protected:13     std::string name;14 15 private:16     static int count;17 };18 19 class Dog : public Pet20 {21 public:22     Dog(std::string theName);23 };24 25 class Cat : public Pet26 {27 public:28     Cat(std::string theName);29 };30 31 int Pet::count = 0;         // 注意这一句:他起码做了两件事32 33 Pet::Pet(std::string theName)34 {35     name = theName;36     count++;37 38     std::cout << "一只宠物出生了,名字叫做: " << name << "\n";39 }40 41 Pet::~Pet()42 {43     count--;44     std::cout << name << "挂掉了\n";45 }46 47 int Pet::getCount()48 {49     return count;50 }51 52 Dog::Dog(std::string theName) : Pet(theName)53 {54 }55 56 Cat::Cat(std::string theName) : Pet(theName)57 {58 }59 60 int main()61 {62     Dog dog("Tom");63     Cat cat("Jerry");64 65     std::cout << "\n已经诞生了" << Pet::getCount() << "只宠物!\n\n";66 67     {68 69         Dog dog_2("Tom_2");70         Cat cat_2("Jerry_2");71 72         std::cout << "\n现在呢,已经诞生了" << Pet::getCount() << "只宠物!\n\n";73 74     }75 76     std::cout << "\n现在还剩下 " << Pet::getCount() << " 只宠物!\n\n";77 78     return 0;79 }[url=][/url]


我们现在要分析,析构器合适执行,那我们就重点观测,小动物是何时挂掉的~
小结:
我们发现,小动物是在main函数中,所有代码执行完之后挂掉的~~(其实就是走出大括号,他们的生命就结束了,析构器执行了)
我们还发现,后诞生的小动物,会首先被送走(析构)。(真是“白毛”送“黑毛”啊,呜呜~~)

加上括号之后,jerry_2和Tom_2,在执行“现在还剩。。。”这句之前就挂掉了!
原因在于,jerry_2和Tom_2被“圈养”在一个大括号之内了,那么这个大括号以内就是他们人生的全部了。程序顺序执行,
一旦走出这个“圈圈”,jerry_2和Tom_2就被析构了~~!!







歡迎光臨 比思論壇 (http://108.170.5.76/) Powered by Discuz! X2.5