在c ++接口方面,什么是(简单理解)窄合同和宽合同? [英] What is (in simple understanding) narrow contract and wide contract in terms of c++ interface(s)?

查看:82
本文介绍了在c ++接口方面,什么是(简单理解)窄合同和宽合同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在介绍一些 c ++ 11 概念时,我遇到了窄合约宽合同

While walking through some c++11 concepts, I came across the terms narrow contract and wide contract.

但是我没有弄清楚为这些合同编写的简单函数示例。

But I failed to figure out a simple function example(s) which is/are written for these contracts.

我可以看到一个简单的函数示例来区分这两个合约吗?

推荐答案

广泛的合同功能对所有可能的输入都有明确定义的行为,而狭窄的合同意味着只有在满足某些先决条件时才能调用该功能。

Wide contract functions have well-defined behavior for all possible inputs, while narrow contracts mean that the functions can only be called when certain preconditions are met.

输入可能还包括全局状态或为其调用成员函数的对象。明确定义的行为可能意味着抛出异常。

"Input" might also include global state or the object for which a member function is called. Well-defined behavior might mean throwing an exception.

例如, std :: vector< int> -s .size()成员函数具有广泛的约定,因为可以在向量的任何实例上调用它(如 std :: vector< int> v; / * v在这里可能发生任何事情... * /; auto s = v.size(); 始终有效)。 operator [](size_t索引)(如 int x = v [10] )的合约范围狭窄,因为只能使用小于 .size()的参数来调用它,否则它是未定义的。但是, .at(size_t i)成员函数(如 int y = v.at(10))具有

For example, std::vector<int>-s .size() member function has a wide contract because it can be called on any instance of a vector (as in std::vector<int> v; /* anything can happen with v here... */; auto s = v.size(); is always valid). The operator[](size_t index) (as in int x = v[10]) has a narrow contract, because it can only be called with a parameter that is less than .size(), otherwise it is undefined. The .at(size_t i) member function (as in int y = v.at(10)) however has a wide contract, because it is specified to throw an exception when the index is out of range.

先决条件并不总是很容易验证:对于诸如<$ c之类的指针,它是一个宽范围的合同,因为它被指定在索引超出范围时引发异常。 $ c> int * p , * 运算符具有较窄的约定,因为您只能在指针指向有效对象时取消引用,但是在取消引用之前验证指针的一般方法。

Preconditions are not always easy to verify: For pointers such as int* p, the * operator has a narrow contract, because you can only dereference a pointer when it points to a valid object, but general way to verify a pointer before dereferencing it.

这篇关于在c ++接口方面,什么是(简单理解)窄合同和宽合同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆