atexit()函数积累记录

函数名: atexit
头文件:#include<stdlib.h>
功 能: 注册终止函数(即main执行结束后调用的函数)
用 法: int atexit(void (*func)(void));
注意:按照ISO C的规定,一个进程可以登记多达32个函数,这些函数将由exit自动调用。atexit()注册的函数类型应为不接受任何参数的void函数,exit调用这些注册函数的顺序与它们 登记时候的顺序相反。同一个函数如若登记多次,则也会被调用多次。

C++11的原文解释:

Set function to be executed on exit
The function pointed by func is automatically called without arguments when the program terminates normally.

If more than one atexit function has been specified by different calls to this function, they are all executed in reverse order as a stack (i.e. the last function specified is the first to be executed at exit).

A single function can be registered to be executed at exit more than once.

If atexit is called after exit, the call may or may not succeed depending on the particular system and library implementation ( unspecified behavior).

If a function registered with atexit throws an exception for which it does not provide a handler when called on termination, terminate is automatically called (C++).

Particular library implementations may impose a limit on the number of functions call that can be registered with atexit, but this cannot be less than 32 function calls.


最后一句话很关键:but this cannot be less than 32 function calls.不能少于32个,而不是网上一些“最多32个”的说法,翻译成“多达32个函数”,也是模棱两可。

Parameters

function
Function to be called. The function shall return no value and take no arguments.

Return Value

A zero value is returned if the function was successfully registered.
If it failed, a non-zero value is returned.


官方example:

/* atexit example */
#include <stdio.h>      /* puts */
#include <stdlib.h>     /* atexit */

void fnExit1 (void)
{
  puts ("Exit function 1.");
}

void fnExit2 (void)
{
  puts ("Exit function 2.");
}

int main ()
{
  atexit (fnExit1);
  atexit (fnExit2);
  puts ("Main function.");
  return 0;
}

Output:


Main function.
Exit function 2.
Exit function 1.





你可能感兴趣的:(c,C++11)