C++学习笔记-2-构造函数和析构函数

问题2. 什么时候执行构造函数和析构函数  22:59:40 2015-07-22

做了一个实验:

#include <iostream>
class Object{
public:
    Object(){
        printf("Create Object
");
    };
    ~Object(){
        printf("Delete Object
");
    }
};
void runObject(){
    Object obj;
    printf("runObject end
");
}
int main(){
//    Object *obj=new Object();
//    delete obj;
    runObject();
    printf("end
");
    return 0;
}

输出为:

Create Object
runObject end
Delete Object
end

在void  runObject()中加一个{}

#include <iostream>
class Object{
public:
    Object(){
        printf("Create Object
");
    };
    ~Object(){
        printf("Delete Object
");
    }
};
void runObject(){
    {
        Object obj;
    }
    printf("runObject end
");
}
int main(){
//    Object *obj=new Object();
//    delete obj;
    runObject();
    printf("end
");
    return 0;
}

输出为:

Create Object
Delete Object
runObject end
end