Contracts for C++getWidget (index i) pre (i > 0) // precondition assertion post (w: w.index() == i); // postcondition assertion ## Proposal: add contract assertions to C++ // precondition assertion // postcondition assertion assertion ## Proposal: add contract assertions to C++ Widget getWidget (index i) pre (i > 0) // precondition assertion post (w: w.index() == i) // postcondition assertion { auto* db = getDatabase(); of consensus. The proposal includes syntax for specifying three kinds of contract assertions: precondition assertions, postcondition assertions, and assertion statements. In addition, we specify four evaluation0 码力 | 181 页 | 4.44 MB | 1 年前3
Better Code: Exploring Validitya beholder ## // - Precondition: x >= 0 double sqrt(double x); - Negative numbers are invalid arguments to sqrt - A declaration of argument validity is called a precondition DEFINITION: An argument imply? 1. Unless a function’s documentation says so, broken arguments are invalid. [implicit precondition] (*this of destructor and assignment are notable exceptions) 2. Class APIs may not give callers org/wiki/Rational_number class rational { public: // Creates an instance with value a/b. // - Precondition: b!=0. rational(unsigned a, unsigned b); bool operator==(const rational & rhs) const;0 码力 | 117 页 | 6.03 MB | 1 年前3
Noexcept: Enabling Testing of Contract Checksto meet, provided the preconditions have been met Example contract for vector::pop_back() : Precondition: the vector is not empty • Postcondition: the last element of the vector has been removed ## Example: signed integer addition (precondition: a + b will not over/underflow) Example: vector::front() (precondition: the vector is not empty) When a precondition is violated, the result is Undefined Postconditions do not have to hold – the contract is broken ## Contract Violations Failure to meet a precondition or postcondition is a bug in the code. • Catching contract violations early results in fewer0 码力 | 90 页 | 1.38 MB | 1 年前3
Better Code: Contractse5a65ff0d/p9_1.jpg) ## Hoare Logic | Preconditions and Postconditions $ \{P\}C\{Q\} $ If precondition P is met, executing C establishes postcondition Q  Tony Hoare ## Hoare Logic | Preconditions and Postconditions ## $ \{P\}C\{Q\} $ If precondition P is met, executing C establishes postcondition Q  Tony Hoare ## Hoare Logic | Preconditions and Postconditions $$ \{P\}C\{Q\} $$ If precondition P is met, executing C establishes postcondition Q 












