核心差異
| 特性 | return | exit() |
| 適用範圍 | 任何函式 | 通常用於子程式/非 main 函式強制結束程式 |
main 中使用 | 需配合回傳型別(int main()) | 無論 main 宣告為 void 或 int,exit(code) 皆能設定程式結束代碼 |
| 物件解構 | 觸發區域物件解構函式(堆疊展開) | 不呼叫區域物件解構函式,直接終止程式 |
| 清理動作 | 執行 atexit 登錄函式、std::ios_base::Init 清理 | 執行 atexit 函式,但跳過堆疊物件解構 |
程式碼示範
#include
#include
using namespace std;
class Test {
public:
Test(int id) : id(id) { cout << "建構 " << id << endl; }
~Test() { cout << "解構 " << id << endl; }
int id;
};
void sub_exit() {
Test t(1); // 區域物件
exit(0); // 程式直接結束,t 不會被解構!
}
void sub_return() {
Test t(2);
return; // 函式返回,t 正常解構
}
int main() {
// exit 在 main 中等同 return 設定結束代碼
// 但 main 為 void 時只能用 exit 回傳代碼
// int main() { exit(1); } 等價於 int main() { return 1; }
}
最佳實務建議
- 正常流程控制:優先使用
return,確保 RAII 機制正常運作(智慧指標、鎖、檔案流自動釋放)。
- 嚴重錯誤/異常情況:若無法透過例外處理機制回傳,或需立即終止(如
abort() 替代),可使用 exit()。
- main 函式:建議宣告
int main() 並使用 return,符合標準並利於移植。