| 特性 | std::endl | "\n" |
|---|---|---|
| 換行 | ✅ 寫入 '\n' | ✅ 寫入 '\n' |
| 刷新緩衝區 | ✅ 呼叫 flush() | ❌ 不刷新 |
| 效能 | 較低 (頻繁 I/O 系統呼叫) | 較高 (累積緩衝批次寫入) |
| 適用場景 | 互動式終端、即時日誌、提示訊息 | 檔案輸出、大量資料、效能敏感路徑 |
// endl 實際相當於:
ostream& endl(ostream& os) {
os.put('\n');
os.flush(); // 強制將緩衝區資料寫入裝置 (終端/檔案)
return os;
}
cout << "Processing..." << endl;) → 用 endl。'\n',最後統一 flush() 或程式結束自動刷新。endl,改用 '\n' + 定期手動 flush()。endl 內部鎖定流物件,多執行緒交錯輸出時較安全;'\n' 需自行加鎖。endl 只是換行」→ 忽略了 flush() 的重大副作用。'\n' 不換行」→ 它換行,只是不刷新。endl 保險」→ 導致大量 write() 系統呼叫,效能暴跌 10-100 倍。endl = '\n' + flush()。預設用 '\n',僅在「必須立即看到輸出」時用 endl。這是 C++ 高效 I/O 的基本功。