Is it right to use exit or return in main?

Asked 2 years ago, Updated 2 years ago, 141 views

Is it right to use exit or return in main?

The main() also has a return type, so I think it's right to use return, but I've seen some codes use exit() together. Which one should I use?

c c++ return

2022-09-22 22:10

1 Answers

When main() writes return, the destructor of the local object is called.

Because exit() does not return, the destructor of the local object is not called. (In some special cases, such as files, the static object will vanish.)

abort() does not destroy any objects (including global/static.

#include <iostream>
using namespace std;

class Foo{
public:
    int num;
    Foo(intn): num(n) { cout << "Call creator: " << num << endl;}
    ~Foo() { cout << "Call the extinct: " << num << endl;}
};
Foo foo0(0);
int main(){
    Foo foo1(1);
    return 0;
}

Output:

Call constructor: 0
Invoke constructor: 1
Calling extinction: 1
Destructor call: 0
#include <iostream>
using namespace std;

class Foo{
public:
    int num;
    Foo(intn): num(n) { cout << "Call creator: " << num << endl;}
    ~Foo() { cout << "Call the extinct: " << num << endl;}
};
Foo foo0(0);
int main(){
    Foo foo1(1);
    exit(0);
}

Output:

Call constructor: 0
Invoke constructor: 1
Destructor call: 0


2022-09-22 22:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.