簡體   English   中英

std::filesystem::exists -- 如果 function 返回 true,我是否需要檢查 std::error_code 值?

[英]std::filesystem::exists -- Do I need to check the std::error_code value if the function returns true?

std::filesystem::exists用於檢查“給定文件狀態或路徑是否對應於現有文件或目錄”。 在我的代碼中,我使用具有以下簽名的定義:

bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept;

我的問題是:如果 function 返回 boolean 值true ,我還需要檢查錯誤代碼ec的值嗎? 或者我可以假設,如果std::filesystem::exists返回true ,那么沒有錯誤並且(bool)ecfalse

例如,假設我有以下內容:

std::error_code ec;
std::filesystem::path fpath = "fname";
bool does_exist = std::filesystem::exists(fpath, ec);
if (does_exist) {
    ...
}

是否有必要在if (does_exist) {... }塊中檢查(bool)ec == false

來自 cppreference:

如果 OS API 調用失敗,則采用std::error_code&參數的重載將其設置為 OS API 錯誤代碼,如果沒有發生錯誤則執行ec.clear()

不,你不需要 最好只在調用失敗時使用它。 任何其他時間ec都不會包含任何有用的信息。

您可以使用if-initializer語句強制執行此操作,因此錯誤代碼僅在可能的最小 scope 內聲明:

std::filesystem::path fpath{"fname"};
if(std::error_code ec{}; !std::filesystem::exists(fpath, ec)) {
    std::cerr << "File system returned the following for \"" << fpath.string() << "\":\nError: " << ec.value() << "\nMessage: " << ec.message();
}

std::filesystem庫直接從相應的Boost 庫演變而來。 作為 Boost 庫(例如 Boost ASIO)中的幾個函數,它提供了兩個使用不同類型的錯誤處理的接口

bool exists(std::filesystem::path const& p);
bool exists(std::filesystem::path const& p, std::error_code& ec) noexcept;

第一個版本使用異常(必須使用try... catch構造捕獲),而第二個版本不使用異常,而是必須評估錯誤代碼。 如果 function 返回false ,則此錯誤代碼可能包含有關失敗的確切原因的其他信息並有助於調試。

不采用 std::error_code& 參數的重載在底層 OS API 錯誤上引發 filesystem_error,以 p 作為第一個路徑參數和 OS 錯誤代碼作為錯誤代碼參數構造。 如果 OS API 調用失敗,則采用 std::error_code& 參數的重載將其設置為 OS API 錯誤代碼,如果沒有發生錯誤則執行 ec.clear()。 如果 memory 分配失敗,任何未標記為 noexcept 的重載都可能拋出 std::bad_alloc。

另一方面,如果 function 返回true ,則可以安全地假設路徑存在

錯誤代碼更輕量級,尤其適用於實時性能代碼、數值模擬和高性能應用程序。 在這些情況下,為了獲得更好的性能,可能會完全關閉編譯過程的異常處理。 另一方面,對於嵌套代碼,錯誤代碼通常更難維護 - 如果例程在某些子功能中失敗 - 您將不得不將錯誤代碼通過幾層傳遞到應該處理錯誤的地方。 這方面的異常更容易維護。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM