C++中如何在main()函数之前执行操作?

多玩YY语音的面试题:C++中如何在main()函数之前执行操作?

           第一反应main()函数是所有函数执行的开始。但是问题是main()函数执行之前如何执行呢?

           联想到MFC里面的 C**App类的theApp对象,其执行顺序就在main函数之前。道理相通,顺理推下,能够想到:如果在main函数之前声明一个类的全局的对象。那么其执行顺序,根据全局对象的生存期和作用域,肯定先于main函数。

示例如下:

class simpleClass  
{  
public:  
       simpleClass( )  
       {  
              cout << "simpleClass constructor.." << endl;  //step2  
       }  
};  
  
   
simpleClass g_objectSimple;         //step1全局对象  
  
int _tmain(int argc, _TCHAR* argv[])  //step3  
{  
       return 0;  
}  
  
可单步调试查看执行顺序为step1、step2、step3。

考虑到全局对象,同理会进一步思考静态对象的作用域。 将上述示例进一步扩展如下:

class simpleClass  
{  
public:  
       simpleClass( )  
       {  
              cout << "simpleClass constructor.." << endl;       //step2   
       }  
};  
  
class simpleClassTwo  
{  
public:  
       static simpleClass m_sSimpleClass;  
};  

simpleClass simpleClassTwo::m_sSimpleClass = simpleClass(); //step1 静态对象  
  
int _tmain(int argc, _TCHAR* argv[])                        //step3  
  
{  
        return 0;  
}  
  
可单步调试查看执行顺序为step1、step2、step3。

至此,我们可以总结出:定义在main( )函数之前的全局对象、静态对象的构造函数在main( )函数之前执行

      再进一步思考,既然可以在main( )函数之前执行全局、静态对象的构造函数。那么有没有函数在main( )函数之后执行呢?

有的,onexit函数。原型如下:

_onexit_t _onexit(

   _onexit_t function

);

_onexit_t_m _onexit_m(

   _onexit_t_m function

);

解释:The _onexit function is passed the address of a function (function) to be called when the program terminates normally. Successive calls to _onexit create a register of functions that are executed in LIFO (last-in-first-out) order. The functions passed to _onexit cannot take parameters.

 

核心点:

1)              执行期——程序执行终止的时候;

2)              传递参数——函数的地址,即函数指针;

3)              执行顺序——后进先出。

 

_onexit is a Microsoft extension. For ANSI portability, use atexit. The _onexit_m version of the function is for mixed mode use.

onexit是微软的扩展版本,标准C++里面应用的是atexit。

【MSDN】示例:

#include <stdlib.h>  
#include <stdio.h>  
/* Prototypes */  
int fn1(void), fn2(void), fn3(void), fn4 (void);  
  
int main( void )  
{  
      _onexit( fn1 );  
      _onexit( fn2 );  
      _onexit( fn3 );  
      _onexit( fn4 );  
      printf( "This is executed first.\n" );  
}  
  
   
int fn1()  
{  
      printf( "next.\n" );  
      return 0;  
}  
  
   
int fn2()  
{  
      printf( "executed " );  
      return 0;  
}  
  
   
int fn3()  
{  
      printf( "is " );  
      return 0;  
}  
  
   
int fn4()  
{  
      printf( "This " );  
      return 0;  
} 

执行结果如下:



显然,读程序可以看出main( )函数执行完毕后又执行了onexit( )函数。




  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值