Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is (in simple understanding) narrow contract and wide contract in terms of c++ interface(s)?

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.

Can I see a simple function example that distinguishes between these two contracts?

like image 268
Pavan Chandaka Avatar asked Jul 11 '18 19:07

Pavan Chandaka


Video Answer


1 Answers

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.

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.

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 there is no general way to verify a pointer before dereferencing it.

like image 83
palotasb Avatar answered Nov 16 '22 02:11

palotasb