c++对象的生命周期


参考链接:https://juejin.cn/post/6844904152833753096

1. 程序对象的生存期

  • 全局对象在程序启动时分配,在程序结束时销毁。

  • 对于局部自动对象,当我们进入其定义所在的程序块时被创建,在离开块时销毁。这个过程由栈自动完成。

  • 局部static对象在第一次使用前分配,在程序结束时销毁。

  • C++还支持动态分配对象。动态分配的对象的生存期与它们在哪里创建是无关的,只有当显式地被释放时,这些对象才会销毁。

2. 程序示例

#include 
using namespace std;
class CPerson{
private:
    int age;
public:
    // 构造函数
    CPerson(){
        cout<<"constructor"<age = age;
        cout<<"constructor "<

输出:

constructor 1
constructor 4
constructor 2
constructor 3
deconstructor 3
constructor 3
deconstructor 3
constructor 5
deconstructor 5
deconstructor 4
deconstructor 2
deconstructor 1