Namespaces
Variants
Views
Actions

std::exit

From cppreference.com
< cpp‎ | utility‎ | program
Revision as of 14:14, 10 September 2013 by P12 (Talk | contribs)

Defined in header <cstdlib>
             void exit( int exit_code );
(until C++11)
[[noreturn]] void exit( int exit_code );
(since C++11)

Causes normal program termination to occur.

Several cleanup steps are performed:

  • destructors of objects with thread local storage duration are called
  • destructors of objects with static storage duration are called
  • functions passed to std::atexit are called. If an exception tries to propagate out of any of the function, std::terminate is called
  • all C streams are flushed and closed
  • files created by std::tmpfile are removed
  • control is returned to the host environment. If exit_code is EXIT_SUCCESS, an implementation-defined status, indicating successful termination is returned. If exit_code is EXIT_FAILURE, an implementation-defined status, indicating unsuccessful termination is returned. In other cases implementation-defined status value is returned.

Stack is not unwound: destructors of variables with automatic storage durations are not called.

Contents

Parameters

exit_code - exit status of the program

Return value

(none)

Example

#include <iostream>
 
class Static {
public:
 
    ~Static() 
    {
        std::cout << "Static dtor\n";
    }
};
 
class Local {
public:
    ~Local() 
    {
        std::cout << "Local dtor\n";
    }
};
 
Static static_variable; // dtor of this object *will* be called
 
void atexit_handler()
{
    std::cout << "atexit handler\n";
}
 
int main()
{
    Local local_variable; // dtor of this object will *not* be called
    const int result = std::atexit(atexit_handler); // handler will be called
 
    if (result != 0) {
        std::cerr << "atexit registration failed\n";
        return EXIT_FAILURE;
    }
 
    std::cout << "test\n";
    std::exit(EXIT_FAILURE);
}

Output:

test
atexit handler
Static dtor

See also

causes abnormal program termination (without cleaning up)
(function) [edit]
registers a function to be called on std::exit() invocation
(function) [edit]
causes quick program termination without completely cleaning up
(function) [edit]