1 2 // Copyright (C) 2008-2018 Lorenzo Caminiti 3 // Distributed under the Boost Software License, Version 1.0 (see accompanying 4 // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). 5 // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html 6 7 #include <boost/contract.hpp> 8 #include <string> 9 #include <cassert> 10 11 //[old replace(std::string & s,unsigned index,char x)12char replace(std::string& s, unsigned index, char x) { 13 char result; 14 boost::contract::old_ptr<char> old_char; // Null, old value copied later... 15 boost::contract::check c = boost::contract::function() 16 .precondition([&] { 17 BOOST_CONTRACT_ASSERT(index < s.size()); 18 }) 19 .old([&] { // ...after preconditions (and invariants) checked. 20 old_char = BOOST_CONTRACT_OLDOF(s[index]); 21 }) 22 .postcondition([&] { 23 BOOST_CONTRACT_ASSERT(s[index] == x); 24 BOOST_CONTRACT_ASSERT(result == *old_char); 25 }) 26 ; 27 28 result = s[index]; 29 s[index] = x; 30 return result; 31 } 32 //] 33 main()34int main() { 35 std::string s = "abc"; 36 char r = replace(s, 1, '_'); 37 assert(s == "a_c"); 38 assert(r == 'b'); 39 return 0; 40 } 41 42