old.cpp 1.1 KB

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