What is the difference between exit and std :: exit in C ++?

What is the difference between exitand std::exitin C ++? I examined it, but I could not find anything.

What is the difference between these two codes:

1

if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
    std::cout << "Error: Can't initialize the SDL \n";
    exit(EXIT_FAILURE);
}

2

if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
    std::cout << "Error: Can't initialize the SDL \n";
    std::exit(EXIT_FAILURE);
}
+4
source share
4 answers

These are two names for the same function that does the same.

Please note, however, that in C ++ std::exit/ exit(no matter how you use it) there is some behavior that is not specified for exitin the C library. In particular,

  • exit first destroys all objects with a storage duration of threads that are associated with the current thread.
  • , , atexit, .
    • , , terminate.
  • :
    • C , , .
    • , tmpfile.
    • , , exit (0 EXIT_SUCCESS = > , EXIT_FAILURE = > , - ).

, .

, exit/std::exit ++. , -, , C- , , , , - . ++, , exit, , , .

, exit, - :

struct my_exit : public std::exception { 
    int value;
    my_exit(int value) : value(value) {}
};

int main() { 
    try {
        // do normal stuff
    }

    catch(my_exit const &e) {
        return e.value;
    }
}

, exit, throw my_exit(whatever_value);. , (.. ), .

+7

exit ( ++) "" C stdlib.h.

std::exit - ++; cstdlib.

++ , .

+7

. exit / ( , , , - ), exit(), ::exit() std::exit() .

Usually you do not want to call exit, because it terminates the program without starting local and global destructors (only atexitregistered functions). Sometimes (rarely) what you want, but in general not — you want to come back instead main.

+1
source

When you announced earlier: using namespace std;there is no difference between std::exitandexit

This declaration avoids spelling the std prefix.

So you can also write coutinsteadstd::cout

+1
source

Source: https://habr.com/ru/post/1649934/


All Articles