static_public.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <cassert>
  7. //[static_public
  8. template<class C>
  9. class make {
  10. public:
  11. static void static_invariant() { // Static class invariants.
  12. BOOST_CONTRACT_ASSERT(instances() >= 0);
  13. }
  14. // Contract for a static public function.
  15. static int instances() {
  16. // Explicit template parameter `make` (check static invariants).
  17. boost::contract::check c = boost::contract::public_function<make>();
  18. return instances_; // Function body.
  19. }
  20. /* ... */
  21. //]
  22. make() : object() {
  23. boost::contract::old_ptr<int> old_instances =
  24. BOOST_CONTRACT_OLDOF(instances());
  25. boost::contract::check c = boost::contract::constructor(this)
  26. .postcondition([&] {
  27. BOOST_CONTRACT_ASSERT(instances() == *old_instances + 1);
  28. })
  29. ;
  30. ++instances_;
  31. }
  32. ~make() {
  33. boost::contract::old_ptr<int> old_instances =
  34. BOOST_CONTRACT_OLDOF(instances());
  35. boost::contract::check c = boost::contract::destructor(this)
  36. .postcondition([&] { // (An example of destructor postconditions.)
  37. BOOST_CONTRACT_ASSERT(instances() == *old_instances - 1);
  38. })
  39. ;
  40. --instances_;
  41. }
  42. C object;
  43. private:
  44. static int instances_;
  45. };
  46. template<class C>
  47. int make<C>::instances_ = 0;
  48. int main() {
  49. struct x {};
  50. make<x> x1, x2, x3;
  51. assert(make<x>::instances() == 3);
  52. return 0;
  53. }