简体   繁体   English

使用核心指南 GSL Expects、Ensures 和narrow_cast 处理错误

[英]Error Handling with Core Guidelines GSL Expects, Ensures, and narrow_cast

I am trying to follow the Cpp Core Guidelines and use GSL where appropriate.我正在尝试遵循 Cpp 核心指南并在适当的情况下使用 GSL。 In particular, I would like to use Expects and Ensures for pre and post-conditions, as well as span , and narrow_cast , but the error handling is not robust and does not provide any diagnostics.特别是,我想将ExpectsEnsures用于前置条件和后置条件,以及spannarrow_cast ,但错误处理并不可靠,并且不提供任何诊断。 When encountering errors GSL simply calls terminate leaving the tester with no clues as to what caused the termination.当遇到错误时,GSL 只是调用terminate ,让测试人员不知道是什么导致了终止。

So my question is: How does one use GSL and keep code robust in the presence of errors?所以我的问题是:如何使用 GSL 并在出现错误的情况下保持代码的健壮性? Or more simply, how to use GSL and get error diagnostics prior to termination?或者更简单地说,如何使用 GSL 并在终止前获得错误诊断?

I don't see an easy way to achieve that.我没有看到实现这一目标的简单方法。 You could write your own terminate handler that gets called by std::terminate , but that has no context of where and why std::terminate was called.您可以编写自己的终止处理程序,该处理程序由std::terminate调用,但这没有关于调用std::terminate ::terminate 的位置和原因的上下文。 Depending on the platform it might be possible to get a backtrace and retrieve some information at least about the caller, but that is not of great help.根据平台的不同,可能会获得回溯并检索至少有关调用者的一些信息,但这并没有太大帮助。

For MS/GSL I provided some code in a pull request that enriches the exception thrown by narrow_cast , but that PR was rejected because it pulls in the streaming library.对于 MS/GSL,我在拉取请求中提供了一些代码,这些代码丰富了narrow_cast引发的异常,但该 PR 被拒绝,因为它拉入了流式库。 Herb Sutter, part of the CppCoreGuidelines committee said: CppCoreGuidelines 委员会成员 Herb Sutter 说:

C++ Core Guidelines editors' call: This seems to be asking for a debugging aid that can be expensive in release mode. C++ 核心指南编辑的电话:这似乎是在要求调试辅助,在发布模式下可能很昂贵。 It could be added in debug mode only, and then only for projects that are not supposed to change their dependencies between debug and release modes (which seems undesirable because it limits use of GSL in such projects).它只能在调试模式下添加,然后仅用于不应该更改其在调试和发布模式之间的依赖关系的项目(这似乎是不可取的,因为它限制了在此类项目中使用 GSL)。 Better would be to use the debugger to view the information if an exception is thrown, such as by setting a breakpoint in the implementation of narrow .如果抛出异常,最好使用调试器查看信息,例如通过在narrow的实现中设置断点。

My branch is deleted, but can be restored if you like to integrate that feature in your code.我的分支已删除,但如果您想将该功能集成到代码中,可以恢复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM