Jas*_*sha 2 c++ error-code c++17
std::filesystem::exists用于检查“给定的文件状态或路径是否对应于现有文件或目录”。在我的代码中,我使用具有以下签名的定义:
bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept;
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果函数返回布尔值true,我还需要检查错误代码的值吗ec?或者我可以假设,如果std::filesystem::exists返回true,则没有错误并且(bool)ec是false?
例如,假设我有以下内容:
std::error_code ec;
std::filesystem::path fpath = "fname";
bool does_exist = std::filesystem::exists(fpath, ec);
if (does_exist) {
...
}
Run Code Online (Sandbox Code Playgroud)
是否需要在区块(bool)ec == false内进行检查if (does_exist) { ... }?
该库直接从相应的Boost库std::filesystem演变而来。作为 Boost 库中的几个函数(例如 Boost ASIO),它提供了两个使用不同类型的错误处理的接口
bool exists(std::filesystem::path const& p);
bool exists(std::filesystem::path const& p, std::error_code& ec) noexcept;
Run Code Online (Sandbox Code Playgroud)
第一个版本使用异常(必须用构造捕获try... catch),而第二个版本则不使用异常,但必须评估错误代码。然后,此错误代码可能包含有关失败的确切原因的附加信息,并有助于在函数返回时进行调试false。
不采用 std::error_code& 参数的重载会在底层操作系统 API 错误上引发 filesystem_error,该错误由 p 作为第一个路径参数和操作系统错误代码作为错误代码参数构造。如果操作系统 API 调用失败,则采用 std::error_code& 参数的重载会将其设置为操作系统 API 错误代码,如果没有发生错误,则执行 ec.clear()。如果内存分配失败,任何未标记为 noexcept 的重载都可能抛出 std::bad_alloc。
true另一方面,如果函数返回,则可以安全地假设该路径存在。
错误代码更加轻量级,特别适合实时高性能代码、数值模拟和高性能应用。在这些情况下,人们可能会完全关闭编译过程的异常处理,以获得更好的性能。另一方面,对于嵌套代码来说,错误代码通常更难维护 - 如果例程在某些子函数中失败 - 您将必须将错误代码通过多个层传递到应该处理错误的位置。这方面的异常更容易维护。