C++ Design by contract
CppCoreGuidelines 中涉及design by contract的内容
I.6: Prefer Expects()
for expressing preconditions
I.8: Prefer Ensures()
for expressing postconditions
ES.65: Don't dereference an invalid pointer
This would carry a cost only when the assertion checking was enabled and would give a compiler/analyzer useful information. This would work even better if/when C++ gets direct support for contracts:
void f3(int* p) // state that p is not supposed to be nullptr
[[expects: p]]
{
int x = *p;
}
NR.3: Don't avoid exceptions
Contracts/assertions: Use GSL's Expects
and Ensures
(until we get language support for contracts)
GSL.assert: Assertions
These assertions are currently macros (yuck!) and must appear in function definitions (only) pending standard committee decisions on contracts and assertion syntax. See the contract proposal; using the attribute syntax, for example, Expects(p)
will become [[expects: p]]
.