在C 中,不同位置定义的对象,构造函数、析构函数被调用的时机都是不一样的。
全局对象最先被调用构造函数,最后被调用析构函数
在main中的对象依次被调用构造函数。在程序结束时,对于普通对象,采取先进后出的原则,调用析构函数。
对于static的静态对象,先调用其他函数中的对象的析构函数,然后再调用main中static对象的析构函数。这一切都是依照LIFO的原则来执行的。
通过以下代码来做这个小实验:
CreateAndDestroy.h
代码语言:javascript复制#pragma once
#include<string>
using namespace std;
#ifndef CREATE_H
#define CREATE_H
class CreateAndDestroy
{
public:
CreateAndDestroy(int, string);
~CreateAndDestroy();//析构函数
private:
int objID;
string message;
};
#endif
CreateAndDestroy.cpp
代码语言:javascript复制#include "CreateAndDestroy.h"
#include<iostream>
using namespace std;
CreateAndDestroy::CreateAndDestroy(int ID, string messageString)
:objID(ID),message(messageString)
{
cout << "Object" << objID << " constructor runs " << message << endl;
}
CreateAndDestroy::~CreateAndDestroy()
{
cout << (objID == 1 || objID == 6 ? "n" : "");
cout << "Object " << objID << " destructor runs " << message << endl;
}
源.cpp
代码语言:javascript复制#include<iostream>
#include"CreateAndDestroy.h"
using namespace std;
void create(void);//函数原型
CreateAndDestroy first(1, "(global before main)");
int main()
{
cout << "nMAIN FUNCTION: EXECUTION BEGINS" << endl;
CreateAndDestroy second(2, "(local automatic in main)");
static CreateAndDestroy third(3, "(local static in main)");
create();
cout << "nMAIN FUNCTION: EXECUTION RESUMES" << endl;
CreateAndDestroy fourth(4, "(local automatic in main)");
cout << "nMAIN FUNCTION: EXECUTION ENDS" << endl;
}
void create(void)
{
cout << "nCREATE FUNCTION: EXECUTION BEGINS" << endl;
CreateAndDestroy fifth(5, "(local automatic in create)");
static CreateAndDestroy sixth(6, "(local static in create)");
CreateAndDestroy seventh(7, "(local automatic in create)");
cout << "nCREATE FUNCTION: EXECUTION ENDS" << endl;
}
转载请注明来源:https://www.longjin666.top/?p=811