0
点赞
收藏
分享

微信扫一扫

C++核心准则边译边学-I.8 表示后置条件最好使用Ensures()


I.8: Prefer ​​Ensures()​​ for expressing postconditions(表示后置条件最好使用Ensures())

Reason(原因)

To make it clear that the condition is a postcondition and to enable tool use.

明确的表示该条件是后置条件,同时也让工具检查成为可能。

Example(示例)

 

void f(){    char buffer[MAX];    // ...    memset(buffer, 0, MAX);    Ensures(buffer[0] == 0);}

 

Note(注意)

Postconditions can be stated in many ways, including comments, ​​if​​​-statements, and ​​assert()​​. This can make them hard to distinguish from ordinary code, hard to update, hard to manipulate by tools, and may have the wrong semantics.

后置条件可以以多种方式表达,包括注释,if语句和assert()。但是使用这些方式表达的后置条件很难从原始代码中区分出来,难以更新,难以被工具处理,还可能会包含错误的语义。

Alternative: Postconditions of the form "this resource must be released" are best expressed by RAII.

其他选项:“这个资源必须被释放”形式的后置条件最好通过RAII体现。

Note(注意)

Ideally, that ​​Ensures​​ should be part of the interface, but that's not easily done. For now, we place it in the definition (function body). Once language support becomes available (e.g., see the contract proposal) we will adopt the standard version of preconditions, postconditions, and assertions.

理想情况下,Ensures应该成为接口的一部分,但这并不容易实现。到目前为止,我们还是将他放到定义(函数体)中。当语言支持可用时(例如,参考contract建议),我们将会导入前置条件,后置条件和断言。

译者注:contract指的是一直在讨论,C++20即将引入的新特性contract。具体可参考:https://cppeurope.com/wp-content/uploads/2018/03/contracts.pdf

Enforcement(实施建议)

(Not enforceable) Finding the variety of ways postconditions can be asserted is not feasible. Warning about those that can be easily identified (​​assert()​​) has questionable value in the absence of a language facility.

(非强制)发现多种确认后置条件的方式是不现实的。警戒那些容易标识(assert())的,由于语言功能的缺失而有疑问的数值。


阅读更多更新文章,请关注微信公众号【面向对象思考】

 

举报

相关推荐

0 条评论