tutorial.qbk 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. [section Tutorial]
  6. This section is a guide to basic usage of this library.
  7. [section Non-Member Functions]
  8. Contracts for non-member functions are programmed using [funcref boost::contract::function].
  9. For example (see [@../../example/features/non_member.cpp =non_member.cpp=]):
  10. [import ../example/features/non_member.cpp]
  11. [non_member]
  12. All necessary header files of this library are included by `#include <boost/contract.hpp>`.
  13. Alternatively, programmers can selectively include only the header files they actually need among =boost/contract/*.hpp= (see __Getting_Started__).
  14. It is possible to specify preconditions, postconditions, and exception guarantees for non-member functions (see __Preconditions__, __Postconditions__, and __Exception_Guarantees__).
  15. The [funcref boost::contract::function] function returns an RAII object that must always be assigned to a local variable of type [classref boost::contract::check] (otherwise this library will generate a run-time error, see [macroref BOOST_CONTRACT_ON_MISSING_CHECK_DECL]).
  16. [footnote
  17. The name of this local variable is arbitrary, but `c` is often used in this documentation for ["c]heck or ["c]aminiti [^;-)] .
  18. ]
  19. Furthermore, C++11 `auto` declarations cannot be used here and the [classref boost::contract::check] type must be explicitly specified (otherwise this library will generate a compile-time error prior C++17 and a run-time error post C++17).
  20. [footnote
  21. *Rationale:*
  22. C++17 guaranteed copy elision on function return value voids the trick this library uses to force a compile-time error when `auto` is incorrectly used instead of [classref boost::contract::check].
  23. The library still generates a run-time error in this case (also on C++17).
  24. In any case, after reading this documentation it should be evident to programmers that `auto` should not be used in [classref boost::contract::check] declarations so this misuse of `auto` should not be an issue in practice.
  25. ]
  26. The function body is programmed right after the declaration of this RAII object.
  27. [note
  28. In some cases, it might be necessary to program some code before the contract.
  29. For example for acquiring resources that will be used while checking the contract like old values, but also to lock mutexes (or other synchronization mechanisms) in multi-threaded programs.
  30. ]
  31. At construction, the [classref boost::contract::check] RAII object for non-member functions does the following (enclosing function entry):
  32. # Check preconditions, by calling the nullary functor [^['r]]`()` passed to `.precondition(`[^['r]]`)`.
  33. At destruction instead (enclosing function exit):
  34. # If the function body did not throw an exception:
  35. # Check postconditions, by calling the nullary functor [^['s]]`()` passed to `.postcondition(`[^['s]]`)`.
  36. # Else:
  37. # Check exception guarantees, by calling the nullary functor [^['e]]`()` passed to `.except(`[^['e]]`)`.
  38. This ensures that non-member function contracts are correctly checked at run-time (see __Function_Calls__).
  39. (Also note that functions will correctly check their contracts even when they are called via function pointers, function objects, etc.)
  40. [note
  41. A non-member function can avoid calling [funcref boost::contract::function] for efficiency but only when it has no preconditions, no postconditions, and no exception guarantees.
  42. ]
  43. [endsect]
  44. [section Preconditions]
  45. When preconditions are specified, they are programmed using a functor [^['r]] passed to `.precondition(`[^['r]]`)` that can be called with no parameters as in [^['r]]`()`.
  46. Contracts that do not have preconditions simply do not call `.precondition(...)`.
  47. Preconditions must appear before postconditions and exception guarantees when these are all present (see __Postconditions__ and __Exception_Guarantees__).
  48. C++11 lambda functions are convenient to program preconditions, but any other nullary functor can be used (see __No_Lambda_Functions__).
  49. [footnote
  50. Lambda functions with no parameters can be programmed in C++11 as `[...] () { ... }` but also equivalently as `[...] { ... }`.
  51. This second from is often used in this documentation omitting the empty parameter list `()` for brevity.
  52. ]
  53. For example, for [funcref boost::contract::function] (similarly for public functions, instead destructors do not have preconditions and constructors use [classref boost::contract::constructor_precondition], see __Public_Functions__, __Destructors__, and __Constructors__):
  54. void f(...) {
  55. boost::contract::check c = boost::contract::function() // Same for all other contracts.
  56. .precondition([&] { // Capture by reference or value...
  57. BOOST_CONTRACT_ASSERT(...); // ...and should not modify captures.
  58. ...
  59. })
  60. ...
  61. ;
  62. ...
  63. }
  64. The precondition functor should capture all the variables that it needs to assert the preconditions.
  65. These variables can be captured by value when the overhead of copying such variables is acceptable.
  66. [footnote
  67. In this documentation preconditions often capture variables by reference to avoid extra copies.
  68. ]
  69. In any case, programmers should not write precondition assertions that modify the value of the captured variables, even when those are captured by reference (see __Constant_Correctness__).
  70. Any code can be programmed in the precondition functor, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex preconditions that might be buggy and also slow to check at run-time).
  71. It is also recommended to use [macroref BOOST_CONTRACT_ASSERT] to program precondition assertions because that enables this library to print informative error messages when the asserted conditions are evaluated to be false (note that this is not a variadic macro, see __No_Macros__):
  72. BOOST_CONTRACT_ASSERT(``[^['boolean-condition]]``)
  73. // Or, if `boolean-condition` contains commas `,` not already within parenthesis `()`...
  74. BOOST_CONTRACT_ASSERT((``[^['boolean-condition]]``)) // ...use extra parenthesis (not a variadic macro).
  75. This library will automatically call the failure handler [funcref boost::contract::precondition_failure] if any of the [macroref BOOST_CONTRACT_ASSERT] conditions are false or, more in general, if calling the functor specified via `.precondition(...)` throws any exception.
  76. By default, this failure handler prints an error message to `std::cerr` and terminates the program calling `std::terminate` (see __Throw_on_Failures__ to change the failure handler to throw exceptions, exit the program with an error code, etc.).
  77. [note
  78. Contracts are most useful when their assertions only use public members that are accessible to the caller so the caller can properly check and use the contract.
  79. In particular, preconditions of a public function or constructor that use non-public members are essentially incorrect because they cannot be fully checked by the caller (in fact, Eiffel generates a compile-time error in this case).
  80. However, this library does not enforce such a constraint and it leaves it up to programmers to only use public members when programming contracts, especially when asserting preconditions (see __Specifications_vs_Implementation__).
  81. ]
  82. [endsect]
  83. [section Postconditions]
  84. When postconditions are specified, they are programmed using a functor [^['s]] passed to `.postcondition(`[^['s]]`)` that can be called with no parameters as in [^['s]]`()`.
  85. Contracts that do not have postconditions simply do not call `.postcondition(...)`.
  86. Postconditions must appear after preconditions but before exception guarantees when these are all present (see __Preconditions__ and __Exception_Guarantees__).
  87. C++11 lambda functions are convenient to program postconditions, but any other nullary functor can be used (see __No_Lambda_Functions__).
  88. For example, for [funcref boost::contract::function] (similarly for all other contracts):
  89. void f(...) {
  90. boost::contract::check c = boost::contract::function() // Same for all other contracts.
  91. ...
  92. .postcondition([&] { // Capture by reference...
  93. BOOST_CONTRACT_ASSERT(...); // ...but should not modify captures.
  94. ...
  95. })
  96. ...
  97. ;
  98. ...
  99. }
  100. The postcondition functor should capture all the variables that it needs to assert the postconditions.
  101. In general, these variables should be captured by reference and not by value (because postconditions need to access the value that these variables will have at function exit, and not the value these variables had when the postcondition functor was first declared).
  102. Postconditions can also capture return and old values (see __Return_Values__ and __Old_Values__).
  103. In any case, programmers should not write postcondition assertions that modify the value of the captured variables, even when those are captured by reference (see __Constant_Correctness__).
  104. Any code can be programmed in the postcondition functor, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex postconditions that might be buggy and slow to check at run-time).
  105. It is also recommended to use [macroref BOOST_CONTRACT_ASSERT] to program postcondition assertions because that enables this library to print informative error messages when the asserted conditions are evaluated to be false (note that this is not a variadic macro, see __No_Macros__):
  106. BOOST_CONTRACT_ASSERT(``[^['boolean-condition]]``)
  107. // Or, if `boolean-condition` has commas `,` not already within parenthesis `()`...
  108. BOOST_CONTRACT_ASSERT((``[^['boolean-condition]]``)) // ...use extra parenthesis (not a variadic macro).
  109. This library will automatically call the failure handler [funcref boost::contract::postcondition_failure] if any of the [macroref BOOST_CONTRACT_ASSERT] conditions are false or, more in general, if calling the functor specified via `.postcondition(...)` throws any exception.
  110. By default, this failure handler prints an error message to `std::cerr` and terminates the program calling `std::terminate` (see __Throw_on_Failures__ to change the failure handler to throw exceptions, exit the program with an error code, etc.).
  111. For non-void virtual public functions and non-void public function overrides, the functor [^['s]] passed to `.postcondition(`[^['s]]`)` is not a nullary functor, instead it is a unary functor taking a variable holding the return value as its one parameter [^['s]]`(`[^['result]]`)` (this is to properly support subcontracting, see __Virtual_Public_Functions__ and __Public_Function_Overrides__).
  112. [endsect]
  113. [section Return Values]
  114. In non-void functions, postconditions might need to access the function return value to program assertions.
  115. In these cases, programmers are responsible to declare a local variable before the contract and to assign it to the return value at function exit (when the function does not throw an exception).
  116. [footnote
  117. The name of the local variable that holds the return value is arbitrary, but `result` is often used in this documentation.
  118. ]
  119. For example, for [funcref boost::contract::function] (similarly for all other contracts):
  120. return_type f(...) {
  121. return_type result; // Must be later assigned to return value.
  122. boost::contract::check c = boost::contract::function() // Same for all other contracts.
  123. ...
  124. .postcondition([&] { // Also capture `result` reference...
  125. BOOST_CONTRACT_ASSERT(result == ...); // ...but should not modify captures.
  126. ...
  127. })
  128. ...
  129. ;
  130. ...
  131. return result = ...; // Assign `result` at each return.
  132. }
  133. At any point where the enclosing function returns, programmers are responsible to assign the result variable to the expression being returned.
  134. This can be done ensuring that /all/ `return` statements in the function are of the form:
  135. ``[^['return-type]]`` result;
  136. ...
  137. return result = ``[^['return-expression]]``; // Assign `result` at each return.
  138. The functor used to program postconditions should capture the result variable by reference and not by value (because postconditions must access the value the result variable will have at function exit, and not the value the result variable had when the postcondition functor was first declared).
  139. The return value should never be used in preconditions, old value copies, or exception guarantees (because the return value is not yet correctly evaluated and set when preconditions are checked, old values are copied, or if the function throws an exception).
  140. In any case, programmers should not modify the result variable in the contract assertions (see __Constant_Correctness__).
  141. It is also possible to declared the result variable using `boost::optional` when the function return type does not have a default constructor, or if the default constructor is too expensive or undesirable to execute when first declaring the result variable (see __Optional_Return_Values__).
  142. Non-void virtual public functions and non-void public function overrides must always declare and use a result variable even when postconditions do not directly use the function return value (this is to properly support subcontracting, see __Virtual_Public_Functions__ and __Public_Function_Overrides__).
  143. [endsect]
  144. [section Old Values]
  145. When old values are used in postconditions or in exception guarantees, programmes are responsible to declare local variables before the contract and to assign them to related old value expressions using [macroref BOOST_CONTRACT_OLDOF].
  146. [footnote
  147. The name of a local variable that holds an old value is arbitrary, but [^old_['variable-name]] is often used in this documentation.
  148. ]
  149. For example, for [funcref boost::contract::function] (similarly for all other contracts):
  150. void f(...) {
  151. boost::contract::old_ptr<old_type> old_var = BOOST_CONTRACT_OLDOF(old_expr);
  152. ... // More old value declarations here if needed.
  153. boost::contract::check c = boost::contract::function() // Same for all other contracts.
  154. ... // Preconditions shall not use old values.
  155. .postcondition([&] { // Capture by reference...
  156. BOOST_CONTRACT_ASSERT(*old_var == ...); // ...but should not modify captures.
  157. ...
  158. })
  159. .except([&] { // Capture by reference...
  160. BOOST_CONTRACT_ASSERT(old_var->...); // ...but should not modify captures.
  161. ...
  162. })
  163. ;
  164. ...
  165. }
  166. Old values are handled by this library using the smart pointer class template [classref boost::contract::old_ptr] (so programmers do not directly manage allocation and deallocation of the pointed memory).
  167. [footnote
  168. *Rationale:*
  169. Old values have to be optional values because they need to be left uninitialized when they are not used because both postconditions and exception guarantees are disabled (defining [macroref BOOST_CONTRACT_NO_POSTCONDITIONS] and [macroref BOOST_CONTRACT_NO_EXCEPTS]).
  170. That is to avoid old value copies when old values are not used, either a pointer or (better) a `boost::optional` could have been used to achieve that.
  171. In addition, old values need to be pointers internally allocated by this library so that they are never copied twice even when calling an overridden function multiple times to check preconditions, postconditions, etc. to implement subcontracting, so a smart pointer class template was used.
  172. ]
  173. The pointed old value type is automatically qualified as `const` (so old values cannot be mistakenly changed by contract assertions, see __Constant_Correctness__).
  174. This library ensures that old value pointers are always not null by the time postconditions and exception guarantees are checked (so programmers can safely dereference and use these pointers in postcondition and exception guarantee assertions using `operator*` and `operator->` without having to check if old value pointers are not null first).
  175. Old values should not be used in preconditions and this library does not guarantee that old value pointers are always not null when preconditions are checked.
  176. [footnote
  177. For example, old value pointers might be null in preconditions when postconditions and exception guarantees are disabled defining [macroref BOOST_CONTRACT_NO_POSTCONDITIONS] and [macroref BOOST_CONTRACT_NO_EXCEPTS] (but also when checking an overridden virtual public function contract via subcontracting, etc.).
  178. ]
  179. See __Old_Values_Copied_at_Body__ for delaying the copy of old values until after class invariants (for constructors, destructors, and public functions) and preconditions are checked (when necessary, this allows to program old value expressions under the simplifying assumption that class invariant and precondition assertions are satisfied already).
  180. [macroref BOOST_CONTRACT_OLDOF] is a variadic macro and it takes an extra parameter when used in virtual public functions or public function overrides (see __Virtual_Public_Functions__ and __Public_Function_Overrides__).
  181. C++11 auto declarations can be used with [macroref BOOST_CONTRACT_OLDOF] for brevity `auto `[^old_['variable-name] = BOOST_CONTRACT_OLDOF(['expression])] (but see also __Old_Value_Requirements__).
  182. See __No_Macros__ to program old values without using [macroref BOOST_CONTRACT_OLDOF] (e.g., on compilers that do not support variadic macros).
  183. [note
  184. This library ensures that old values are copied only once.
  185. This library also ensures that old values are never copied when postconditions and exception guarantees are disabled defining both [macroref BOOST_CONTRACT_NO_POSTCONDITIONS] and [macroref BOOST_CONTRACT_NO_EXCEPTS] (note that both these two macros must be defined, defining only [macroref BOOST_CONTRACT_NO_POSTCONDITIONS] or only [macroref BOOST_CONTRACT_NO_EXCEPTS] is not sufficient to prevent the run-time cost of old value copies).
  186. ]
  187. [endsect]
  188. [section Exception Guarantees]
  189. When exception guarantees are specified, they are programmed using a functor [^['e]] passed to `.except(`[^['e]]`)` that can be called with no parameters as in [^['e]]`()`.
  190. Contracts that do not have exception guarantees simply do not call `.except(...)`.
  191. Exception guarantees must appear after both preconditions and postconditions when these are all present (see __Preconditions__ and __Postconditions__).
  192. C++11 lambda functions are convenient to program exception guarantees, but any other nullary functor can be used (see __No_Lambda_Functions__).
  193. For example, for [funcref boost::contract::function] (similarly for all other contracts):
  194. void f(...) {
  195. boost::contract::check c = boost::contract::function() // Same for all other contracts.
  196. ...
  197. .except([&] { // Capture by reference...
  198. BOOST_CONTRACT_ASSERT(...); // ...but should not modify captures.
  199. ...
  200. })
  201. ;
  202. ...
  203. }
  204. The exception guarantee functor should capture all the variables that it needs to assert the exception guarantees.
  205. In general, these variables should be captured by reference and not by value (because exception guarantees need to access the value that these variables will have when the function throws, and not the value these variables had when the exception guarantee functor was first declared).
  206. Exception guarantees can also capture old values (see __Old_Values__) but they should not access the function return value instead (because the return value is not be properly set when the function throws an exception).
  207. In any case, programmers should not write exception guarantee assertions that modify the value of the captured variables, even when those are captured by reference (see __Constant_Correctness__).
  208. [note
  209. In real production code, it might be difficult to program meaningful exception guarantees without resorting to expensive old value copies that will slow down execution.
  210. Therefore, the authors recognize that exception guarantees, even if supported by this library, might not be used often in practice (and they are not used in most of the examples listed in the rest of this documentation).
  211. In any case, these performance considerations are ultimately left to programmers and their specific application domains.
  212. ]
  213. Any code can be programmed in the exception guarantee functor, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex exception guarantees that might be buggy and slow to check at run-time).
  214. It is also recommended to use [macroref BOOST_CONTRACT_ASSERT] to program exception guarantee assertions because that enables this library to print informative error messages when the asserted conditions are evaluated to be false (note that this is not a variadic macro, see __No_Macros__):
  215. BOOST_CONTRACT_ASSERT(``[^['boolean-condition]]``)
  216. // Or, if `boolean-condition` has commas `,` not already within parenthesis `()`...
  217. BOOST_CONTRACT_ASSERT((``[^['boolean-condition]]``)) // ...use extra parenthesis (not a variadic macro).
  218. This library will automatically call the failure handler [funcref boost::contract::except_failure] if any of the [macroref BOOST_CONTRACT_ASSERT] conditions are false or, more in general, if calling the functor specified via `.except(...)` throws any exception.
  219. By default, this failure handler prints an error message to `std::cerr` and terminates the program calling `std::terminate` (see __Throw_on_Failures__ to change the failure handler to exit the program with an error code or to take some other custom action).
  220. [note
  221. While it is technically possible for programmers to specify an exception guarantee handler that throws an exception in case of an exception guarantee failure, this will force C++ to terminate the program.
  222. That is because the handler will throw an exception while there is already an active exception on the stack (the exception thrown by the function body that caused the exception guarantees to be checked in the first place).
  223. Therefore, programmers should not change the exception guarantee failure handler to throw exceptions.
  224. ]
  225. [endsect]
  226. [section Class Invariants]
  227. Public member functions, constructors, and destructors can be programmed to also check class invariants.
  228. When class invariants are specified, they are programmed in a public `const` function named `invariant` taking no argument and returning `void`.
  229. Classes that do not have invariants, simply do not declare the `invariant` function.
  230. [footnote
  231. This library uses template meta-programming (SFINAE-based introspection techniques) to check invariants only for classes that declare a member function named by [macroref BOOST_CONTRACT_INVARIANT_FUNC].
  232. ]
  233. For example:
  234. class u {
  235. public: // Must be public.
  236. void invariant() const { // Must be const.
  237. BOOST_CONTRACT_ASSERT(...);
  238. ...
  239. }
  240. ...
  241. };
  242. This member function must be `const` because contracts should not modify the object state (see __Constant_Correctness__).
  243. This library will generate a compile-time error if the `const` qualifier is missing (unless [macroref BOOST_CONTRACT_PERMISSIVE] is defined).
  244. Any code can be programmed in the `invariant` function, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex invariants that might be buggy and slow to check at run-time).
  245. It is also recommended to use [macroref BOOST_CONTRACT_ASSERT] to program class invariant assertions because that enables this library to print informative error messages when the asserted conditions are evaluated to be false (note that this is not a variadic macro, see __No_Macros__):
  246. BOOST_CONTRACT_ASSERT(``[^['boolean-condition]]``)
  247. // Or, if `boolean-condition` has commas `,` not already within parenthesis `()`...
  248. BOOST_CONTRACT_ASSERT((``[^['boolean-condition]]``)) // ...use extra parenthesis (not a variadic macro).
  249. This library will automatically call failure handlers [funcref boost::contract::entry_invariant_failure] or [funcref boost::contract::exit_invariant_failure] if any of the [macroref BOOST_CONTRACT_ASSERT] conditions are false or, more in general, if the `invariant` function throws an exception when invariants are checked at function entry or exit respectively.
  250. By default, these handlers print an error message to `std::cerr` and terminate the program calling `std::terminate` (see __Throw_on_Failures__ to change these failure handlers to throw exceptions, exit the program with an error code, etc.).
  251. See __Access_Specifiers__ to avoid making the `invariant` member function `public`.
  252. [footnote
  253. In this documentation the `invariant` member function is often declared `public` for simplicity.
  254. However, in production code it might not be acceptable to augment the public members of a class adding the `invariant` function (and that can be avoided using [classref boost::contract::access] as explained in __Access_Specifiers__).
  255. ]
  256. See [macroref BOOST_CONTRACT_INVARIANT_FUNC] to use a name different from `invariant` (e.g., because `invariant` clashes with other names in user-defined classes).
  257. [note
  258. Contract assertions are not checked (not even class invariants) when data members are accessed directly (this is different from Eiffel where even accessing public data members checks class invariants).
  259. Therefore, it might be best for both `class`es and `struct`s (and also `union`s, see __Unions__) that have invariants to have no mutable public data members and to access data members publicly only via appropriate public functions (e.g., setters and getters) that can be programmed to check the class invariants using this library.
  260. ]
  261. See __Volatile_Public_Functions__ to program invariants for classes with `volatile` public functions.
  262. [heading Static Class Invariants]
  263. Static public functions can be programmed to check static class invariants.
  264. When static class invariants are specified, they are programmed in a public `static` function named `static_invariant` taking no argument and returning `void`.
  265. Classes that do not have static class invariants, simply do not declare the `static_invariant` function.
  266. [footnote
  267. This library uses template meta-programming (SFINAE-based introspection techniques) to check static invariants only for classes that declare a member function named by [macroref BOOST_CONTRACT_STATIC_INVARIANT_FUNC].
  268. ]
  269. For example:
  270. class u {
  271. public: // Must be public.
  272. static void static_invariant() { // Must be static.
  273. BOOST_CONTRACT_ASSERT(...);
  274. ...
  275. }
  276. ...
  277. };
  278. This member function must be `static` (and it correctly cannot access the object `this`).
  279. This library will generate a compile-time error if the `static` classifier is missing (unless the [macroref BOOST_CONTRACT_PERMISSIVE] macro is defined).
  280. Any code can be programmed in the `static_invariant` function, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex static invariants that might be buggy and slow to check at run-time).
  281. It is also recommended to use [macroref BOOST_CONTRACT_ASSERT] to program the assertions because that enables this library to print informative error messages when the asserted conditions are evaluated to be false (note that this is not a variadic macro, see __No_Macros__):
  282. BOOST_CONTRACT_ASSERT(``[^['boolean-condition]]``)
  283. // Or, if `boolean-condition` has commas `,` not already within parenthesis `()`...
  284. BOOST_CONTRACT_ASSERT((``[^['boolean-condition]]``)) // ...use extra parenthesis (not a variadic macro).
  285. This library will automatically call failure handlers [funcref boost::contract::entry_invariant_failure] or [funcref boost::contract::exit_invariant_failure] if any of the [macroref BOOST_CONTRACT_ASSERT] conditions are false or, more in general, if the `static_invariant` function throws an exception when invariants are checked at function entry or exit respectively.
  286. By default, these handlers print an error message to `std::cerr` and terminate the program calling `std::terminate` (see __Throw_on_Failures__ to change these failure handlers to throw exceptions, exit the program with an error code, etc.).
  287. See __Access_Specifiers__ to avoid making `static_invariant` member function `public`.
  288. [footnote
  289. In this documentation the `static_invariant` member function is often declared `public` for simplicity.
  290. However, in production code it might not be acceptable to augment the public members of a class adding the `static_invariant` function (and that can be avoided using [classref boost::contract::access] as explained in __Access_Specifiers__).
  291. ]
  292. See [macroref BOOST_CONTRACT_STATIC_INVARIANT_FUNC] to use a name different from `static_invariant` (e.g., because `static_invariant` clashes with other names in user-defined classes).
  293. [footnote
  294. *Rationale:*
  295. In C++, it is not possible to overload a member function based on the `static` classifier.
  296. Therefore, this library has to use different names for the member functions checking non-static and static class invariants (namely for [macroref BOOST_CONTRACT_INVARIANT_FUNC] and for [macroref BOOST_CONTRACT_STATIC_INVARIANT_FUNC]).
  297. ]
  298. [endsect]
  299. [section Constructors]
  300. Contracts for constructors are programmed using the [funcref boost::contract::constructor] function and the [classref boost::contract::constructor_precondition] base class.
  301. For example (see [@../../example/features/public.cpp =public.cpp=]):
  302. [import ../example/features/public.cpp]
  303. [public_class_begin]
  304. [public_constructor]
  305. [public_class_end]
  306. It is not possible to specify preconditions using `.precondition(...)` for constructors (this library will generate a compile-time error if `.precondition(...)` is used on the object returned by [funcref boost::contract::constructor]).
  307. Constructor preconditions are specified using the [classref boost::contract::constructor_precondition] base class instead (same considerations as the ones made in __Preconditions__ apply also to the precondition functor passed to [classref boost::contract::constructor_precondition]).
  308. Programmes should not access the object `*this` from constructor preconditions (because the object does not exists yet before the constructor body is executed).
  309. [footnote
  310. See __No_Lambda_Functions__ to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
  311. ]
  312. Constructors without preconditions simply do not explicitly initialize the [classref boost::contract::constructor_precondition] base (because [classref boost::contract::constructor_precondition] default constructor checks no contract).
  313. When the [classref boost::contract::constructor_precondition] base class is used:
  314. [footnote
  315. There is a MSVC bug that was fixed in MSVC 2013 for which lambdas cannot be used in constructor member initialization lists for templates.
  316. On MSVC compilers with that bug, an extra (static) member function can be used (together with `bind` and `cref` as needed) to program constructor preconditions instead of using lambdas (see __No_Lambda_Functions__).
  317. ]
  318. * It should be specified as the /first/ class in the inheritance list (so constructor preconditions are checked before initializing any other base class or data member).
  319. * Its inheritance access specifier should always be `private` (so this extra base class does not alter the public inheritance tree of its derived classes).
  320. * It should never be declared as a `virtual` base (because virtual bases are initialized only once across the entire inheritance hierarchy preventing preconditions of other base classes from being checked).
  321. * It takes the derived class as template parameter.
  322. [footnote
  323. *Rationale:*
  324. The [classref boost::contract::constructor_precondition] takes the derived class as its template parameter (using the Curiously Recursive Template Pattern, CRTP) so the instantiated template type is unique for each derived class.
  325. This always avoids base class ambiguity resolution errors even when multiple inheritance is used.
  326. Note that, as already mentioned, virtual inheritance could not be used instead of the template parameter here to resolve ambiguities (because virtual bases are initialized only once by the outer-most derived class, and that would not allow to properly check preconditions of all base classes).
  327. ]
  328. [note
  329. A class can avoid inheriting from [classref boost::contract::constructor_precondition] for efficiency but only when all its constructors have no preconditions.
  330. ]
  331. It is possible to specify postconditions for constructors (see __Postconditions__), but programmers should not access the old value of the object `*this` in constructor postconditions (because the object did not exist yet before the constructor body was executed).
  332. [footnote
  333. See __No_Lambda_Functions__ to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
  334. ]
  335. It is also possible to specify exceptions guarantees for constructors (see __Exception_Guarantees__), but programmers should not access the object `*this` or its old value in constructor exception guarantees (because the object did not exist before executing the constructor body and it was not properly constructed given the constructor body threw an exception).
  336. [footnote
  337. See __No_Lambda_Functions__ to enforce these constraints at compile-time (but not recommended because of extra boiler-plate code).
  338. ]
  339. The [funcref boost::contract::constructor] function takes `this` as a parameter (because constructors check class invariants, see __Class_Invariants__).
  340. The [funcref boost::contract::constructor] function returns an RAII object that must always be assigned to a local variable of type [classref boost::contract::check] (otherwise this library will generate a run-time error, see [macroref BOOST_CONTRACT_ON_MISSING_CHECK_DECL]).
  341. Furthermore, C++11 `auto` declarations cannot be used here and the [classref boost::contract::check] type must be explicitly specified (otherwise this library will generate a compile-time error prior C++17 and a run-time error post C++17).
  342. The constructor body is programmed right after the declaration of this RAII object.
  343. At construction, the [classref boost::contract::check] RAII object for constructors does the following (enclosing constructor entry):
  344. # Check static class invariants, by calling [^['type-of]]`(*this)::static_invariant()` (but not non-static class invariants because the object does not exist yet).
  345. At destruction instead (enclosing constructor exit):
  346. # Check static class invariants, by calling [^['type-of]]`(*this)::static_invariant()`.
  347. # If the constructor body did not throw an exception:
  348. # Check non-static class invariants, by calling `this->invariant()`.
  349. # Check postconditions, by calling the nullary functor [^['s]]`()` passed to `.postcondition(`[^['s]]`)`.
  350. # Else:
  351. # Check exception guarantees, by calling the nullary functor [^['e]]`()` passed to `.except(`[^['e]]`)`.
  352. This together with C++ object construction mechanism of base classes and the use of [classref boost::contract::constructor_precondition] ensures that the constructor contracts are correctly checked at run-time (see __Constructor_Calls__).
  353. [note
  354. A constructor can avoid calling [funcref boost::contract::constructor] for efficiency but only when it has no postconditions, no exception guarantees, and its class has no invariants (even if [funcref boost::contract::constructor] is not used by a derived class, contracts of base class constructors will still be correctly checked by C++ object construction mechanism).
  355. The default constructor and copy constructor automatically generated by C++ will not check contracts.
  356. Therefore, unless these constructors are not public or they have no preconditions, no postconditions, no exception guarantees, and their class has no invariants, programmers should manually define them using [funcref boost::contract::constructor] and [classref boost::contract::constructor_precondition].
  357. Similar considerations apply to all other constructors automatically generated by C++ (e.g., the move constructor).
  358. ]
  359. [heading Private and Protected Constructors]
  360. Private and protected constructors can omit [funcref boost::contract::constructor] (because they are not part of the public interface of the class so they are not required to check class invariants, see __Constructor_Calls__).
  361. They could still use [classref boost::contract::constructor_precondition] to check preconditions before member initializations, and even use [funcref boost::contract::function] (but not [funcref boost::contract::constructor]) to only check postconditions and exception guarantees without checking class invariants and without calling `.precondition(...)` (see __Private_and_Protected_Functions__).
  362. For example:
  363. class u : private boost::contract::constructor_precondition<u> {
  364. protected:
  365. // Contract for a protected constructor (same for private constructors).
  366. u() : // Still use this base class to check constructor preconditions.
  367. boost::contract::constructor_precondition<u>([&] {
  368. BOOST_CONTRACT_ASSERT(...);
  369. ...
  370. })
  371. {
  372. // Following will correctly not check class invariants.
  373. boost::contract::check c = boost::contract::function()
  374. // Do not use `.precondition(...)` here.
  375. .postcondition([&] {
  376. BOOST_CONTRACT_ASSERT(...);
  377. ...
  378. })
  379. .except([&] {
  380. BOOST_CONTRACT_ASSERT(...);
  381. ...
  382. })
  383. ;
  384. ... // Constructor body.
  385. }
  386. ...
  387. };
  388. [endsect]
  389. [section Destructors]
  390. Contracts for destructors are programmed using [funcref boost::contract::destructor].
  391. For example (see [@../../example/features/public.cpp =public.cpp=]):
  392. [public_class_begin]
  393. [public_destructor]
  394. [public_class_end]
  395. It is not possible to specify preconditions for destructors (this library will generate a compile-time error if `.precondition(...)` is used here and that is because destructors can be called at any time after construction so they have no precondition).
  396. It is possible to specify postconditions for destructors (see __Postconditions__, and also __Static_Public_Functions__ for an example), but programmers should not access the object `*this` in destructor postconditions (because the object no longer exists after the destructor body has been executed).
  397. [footnote
  398. See __No_Lambda_Functions__ to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
  399. ]
  400. It is also possible to specify exceptions guarantees for destructors (see __Exception_Guarantees__, even if destructors should usually be programmed to not throw exceptions in C++, in fact destructors are implicitly declared `noexcept` since C++11).
  401. [footnote
  402. Exceptions guarantees in destructors can access both the object `*this` and its old value because the object existed before executing the destructor body and it still exists given the destructor body failed throwing an exception so technically the object should still be properly constructed and satisfy its class invariants.
  403. ]
  404. The [funcref boost::contract::destructor] function takes `this` as a parameter (because destructors check class invariants, see __Class_Invariants__).
  405. The [funcref boost::contract::destructor] function returns an RAII object that must always be assigned to a local variable of type [classref boost::contract::check] (otherwise this library will generate a run-time error, see [macroref BOOST_CONTRACT_ON_MISSING_CHECK_DECL]).
  406. Furthermore, C++11 `auto` declarations cannot be used here and the [classref boost::contract::check] type must be explicitly specified (otherwise this library will generate a compile-time error prior C++17 and a run-time error post C++17).
  407. The destructor body is programmed right after the declaration of this RAII object.
  408. At construction, the [classref boost::contract::check] RAII object for destructors does the following (enclosing destructor entry):
  409. # Check static and non-static class invariants, by calling ['[^type-of]]`(*this)::static_invariant()` __AND__ `this->invariant()`.
  410. At destruction instead (enclosing destructor exit):
  411. # Check static class invariants, by calling [^['type-of]]`(*this)::static_invariant()`.
  412. # If the destructor body did not throw an exception:
  413. # Check postconditions, by calling the nullay functor [^['s]]`()` passed to `.postcondition(`[^['s]]`)`.
  414. # Else (even if destructors should generally be programmed not to throw in C++):
  415. # Check non-static class invariants, by calling `this->invariant()` (because the object was not successfully destructed).
  416. # Check exception guarantees, by calling the nullary functor [^['e]]`()` passed to `.except(`[^['e]]`)`.
  417. This together with C++ object destruction mechanism of base classes ensures that destructor contracts are correctly checked at run-time (see __Destructor_Calls__).
  418. [note
  419. A destructor can avoid calling [funcref boost::contract::destructor] for efficiency but only when it has no postconditions, no exception guarantees, and its class has no invariants (even if [funcref boost::contract::destructor] is not used by a derived class, contracts of base class destructors will still be correctly checked by C++ object destruction mechanism).
  420. The default destructor automatically generated by C++ will not check contracts.
  421. Therefore, unless the destructor is not public or it has no postconditions, no exception guarantees, and its class has no invariants, programmers should manually define it using [funcref boost::contract::destructor].
  422. ]
  423. [heading Private and Protected Destructors]
  424. Private and protected destructors can omit [funcref boost::contract::destructor] (because they are not part of the public interface of the class so they are not required to check class invariants, see __Destructor_Calls__).
  425. They could use [funcref boost::contract::function] (but not [funcref boost::contract::destructor]) to only check postconditions and exception guarantees without checking class invariants and without calling `.precondition(...)` (see __Private_and_Protected_Functions__).
  426. For example:
  427. class u {
  428. protected:
  429. // Contract for a protected destructor (same for private destructors).
  430. virtual ~u() {
  431. // Following will correctly not check class invariants.
  432. boost::contract::check c = boost::contract::function()
  433. // Do not use `.precondition(...)` here.
  434. .postcondition([&] {
  435. BOOST_CONTRACT_ASSERT(...);
  436. ...
  437. })
  438. // Could use `.except(...)` here in rare cases of destructors declared to throw.
  439. ;
  440. ... // Destructor body.
  441. }
  442. ...
  443. };
  444. [endsect]
  445. [section Public Functions]
  446. Contracts for public functions are programmed using [funcref boost::contract::public_function].
  447. In this section, let's consider public functions that are not static, not virtual, and do not override any function from base classes.
  448. For example (see [@../../example/features/public.cpp =public.cpp=]):
  449. [public_class_begin]
  450. [public_function]
  451. [public_class_end]
  452. It is possible to specify preconditions, postconditions, and exception guarantees for public functions (see __Preconditions__, __Postconditions__, and __Exception_Guarantees__).
  453. When called from non-static public functions, the [funcref boost::contract::public_function] function takes `this` as a parameter (because public functions check class invariants, see __Class_Invariants__).
  454. The [funcref boost::contract::public_function] function returns an RAII object that must always be assigned to a local variable of type [classref boost::contract::check] (otherwise this library will generate a run-time error, see [macroref BOOST_CONTRACT_ON_MISSING_CHECK_DECL]).
  455. Furthermore, C++11 `auto` declarations cannot be used here and the [classref boost::contract::check] type must be explicitly specified (otherwise this library will generate a compile-time error prior C++17 and a run-time error post C++17).
  456. The public function body is programmed right after the declaration of this RAII object.
  457. At construction, the [classref boost::contract::check] RAII object for public functions does the following (enclosing public function entry):
  458. # Check static and non-static class invariants, by calling [^['type-of]]`(*this)::static_invariant()` __AND__ `this->invariant()`.
  459. # Check preconditions, by calling the nullary functor [^['r]]`()` passed to `.precondition(`[^['r]]`)`.
  460. At destruction instead (enclosing public function exit):
  461. # Check static and non-static class invariants, by calling [^['type-of]]`(*this)::static_invariant()` __AND__ `this->invariant()` (even if the function body threw an exception).
  462. # If the function body did not throw an exception:
  463. # Check postconditions, by calling the nullary functor [^['s]]`()` passed to `.postcondition(`[^['s]]`)`.
  464. # Else:
  465. # Check exception guarantees, by calling the nullary functor [^['e]]`()` passed to `.except(`[^['e]]`)`.
  466. This ensures that public function contracts are correctly checked at run-time (see __Public_Function_Calls__).
  467. [note
  468. A public function can avoid calling [funcref boost::contract::public_function] for efficiency but only when it has no preconditions, no postconditions, no exception guarantees, it is not virtual, it does not override any virtual function, and its class has no invariants.
  469. The default copy assignment operator automatically generated by C++ will not check contracts.
  470. Therefore, unless this operator is not public or it has no preconditions, no postconditions, no exception guarantees, and its class has no invariants, programmers should manually define it using [funcref boost::contract::public_function].
  471. Similar considerations apply to all other operators automatically generated by C++ (e.g., the move operator).
  472. ]
  473. [endsect]
  474. [section Virtual Public Functions]
  475. Contracts for public functions are programmed using [funcref boost::contract::public_function].
  476. In this section, let's consider public functions that are virtual but that do not override any function from base classes.
  477. For example (see [@../../example/features/public.cpp =public.cpp=]):
  478. [public_class_begin]
  479. [public_virtual_function]
  480. [public_class_end]
  481. Virtual public functions must declare an extra trailing parameter of type [classref boost::contract::virtual_]`*` with default value `0` (i.e., `nullptr`).
  482. [footnote
  483. The name of this extra parameter is arbitrary, but `v` is often used in this documentation.
  484. ]
  485. This extra parameter is the last parameter and it has a default value so it does not alter the calling interface of the virtual function (callers will rarely, if ever, have to explicitly deal with this extra parameter a part from when manipulating the virtual function type directly for function pointer type-casting, etc.).
  486. Programmers must pass the extra virtual parameter as the very first argument to all [macroref BOOST_CONTRACT_OLDOF] and [funcref boost::contract::public_function] calls in the virtual public function definition.
  487. [footnote
  488. *Rationale:*
  489. The [classref boost::contract::virtual_]`*` parameter is used by this library to determine that a function is virtual (in C++ it is not possible to introspect if a function is declared `virtual`).
  490. Furthermore, this parameter is internally used by this library to implement subcontracting (specifically to pass result and old values that are evaluated by the overriding function to the contracts of overridden virtual functions in base classes, and also to check preconditions, postconditions, and exception guarantees of overridden virtual functions in __OR__ and __AND__ with contracts of the overriding virtual function).
  491. ]
  492. When called from virtual public functions, the [funcref boost::contract::public_function] function takes `this` as a parameter (because public functions check class invariants, see __Class_Invariants__).
  493. For virtual public functions returning `void`:
  494. class u {
  495. public:
  496. // A void virtual public function (that does not override).
  497. virtual void f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) {
  498. boost::contract::check c = boost::contract::public_function(
  499. v, this) // No result parameter...
  500. .precondition([&] { ... })
  501. .postcondition([&] { ... }) // ...so nullary functor.
  502. .except([&] { ... })
  503. ;
  504. ...
  505. }
  506. ...
  507. }
  508. For virtual public functions not returning `void`, programmers must also pass a reference to the function return value as the second argument to [funcref boost::contract::public_function].
  509. In this case, the library will pass this return value reference to the postcondition functor that must therefore take one single argument matching the return type, otherwise this library will generate a compile-time error (the functor parameter can be a constant reference `const&` to avoid extra copies of the return value):
  510. [footnote
  511. *Rationale:*
  512. The extra function result parameter taken by the functor passed to `.postcondition(...)` is used by this library to pass the return value evaluated by the overriding function to all its overridden virtual functions to support subcontracting.
  513. ]
  514. class u {
  515. public:
  516. // A void virtual public function (that does not override).
  517. virtual t f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) {
  518. t result;
  519. boost::contract::check c = boost::contract::public_function(
  520. v, result, this) // Result parameter...
  521. .precondition([&] { ... })
  522. .postcondition([&] (t const& result) { ... }) // ...so unary functor.
  523. .except([&] { ... })
  524. ;
  525. ... // Assign `result` at each return.
  526. }
  527. ...
  528. }
  529. [important
  530. It is the responsibility of the programmers to pass the extra virtual parameter `v` to all [macroref BOOST_CONTRACT_OLDOF] and [funcref boost::contract::public_function] calls within virtual public functions, and also to pass the return value reference after `v` to [funcref boost::contract::public_function] for non-void virtual public functions.
  531. This library cannot automatically generate compile-time errors if programmers fail to do so (but in general this will prevent the library from correctly checking contracts at run-time).
  532. [footnote
  533. *Rationale:*
  534. This library does not require programmers to specify the function type when using [funcref boost::contract::public_function] for non-overriding virtual public functions.
  535. Therefore, this library does not know if the enclosing function has a non-void return type so it cannot check if the return value reference is passed as required for non-overriding virtual public functions.
  536. Instead the function type is passed to this library for virtual public function overrides and that also allows this library to give a compile-time error if the return value reference is missing in those cases.
  537. ]
  538. *Mnemonics:*
  539. [:When `v` is present, always pass it as the first argument to [funcref boost::contract::public_function] and [macroref BOOST_CONTRACT_OLDOF].]
  540. [:Always pass `result` to [funcref boost::contract::public_function] right after `v` for non-void functions.]
  541. ]
  542. For the rest, considerations made in __Public_Functions__ apply to virtual public functions as well.
  543. [note
  544. A virtual public function should always call [funcref boost::contract::public_function] (even if it has no preconditions, no postconditions, no exception guarantees, and its class has no invariants), otherwise this library will not be able to correctly use it for subcontracting.
  545. ]
  546. [endsect]
  547. [section Public Function Overrides (Subcontracting)]
  548. Contracts for public functions are programmed using [funcref boost::contract::public_function].
  549. In this section, let's consider public functions (virtual or not) that override virtual public functions from one or more of their public base classes.
  550. For example (see [@../../example/features/public.cpp =public.cpp=]):
  551. [footnote
  552. In this documentation, function overrides are often marked with the code comment `/* override */`.
  553. On compilers that support C++11 virtual specifiers, the `override` identifier can be used instead (`override` is not used in the documentation simply because virtual specifiers are not widely supported yet, even by compilers that support C++11 lambda functions).
  554. ]
  555. [public_derived_class_begin]
  556. [public_function_override]
  557. [public_derived_class_end]
  558. The extra `typedef` declared using [macroref BOOST_CONTRACT_BASE_TYPES] is required by this library for derived classes and it is internally used to detect base classes for subcontracting (see __Base_Classes__).
  559. This library will generate a compile-time error if there is no suitable virtual function to override in any of the public base classes for subcontracting.
  560. [footnote
  561. The compile-time error generated by the library in this case is similar in principle to the error generated by the C++11 `override` specifier, but it is limited to functions with the extra [classref boost::contract::virtual_]`*` parameter and searched recursively only in `public` base classes passed to [macroref BOOST_CONTRACT_BASE_TYPES] because only those are considered for subcontracting.
  562. ]
  563. When called from public function overrides, the [funcref boost::contract::public_function] function template takes an explicit template argument `override_`[^['function-name]] that must be defined using [macroref BOOST_CONTRACT_OVERRIDE]:
  564. BOOST_CONTRACT_OVERRIDE(``[^['function-name]]``)
  565. This can be declared at any point in the public section of the enclosing class (see __Access_Specifiers__ to use [macroref BOOST_CONTRACT_OVERRIDE] also in a non-public section of the class).
  566. [macroref BOOST_CONTRACT_OVERRIDE] is used only once in a class for a given function name and overloaded functions can reuse the same [^override_['function-name]] definition (see __Function_Overloads__).
  567. [macroref BOOST_CONTRACT_NAMED_OVERRIDE] can be used to generate a name different than [^override_['function-name]] (e.g., to avoid generating C++ reserved names containing double underscores "`__`" for function names that already start with an underscore "`_`", see __Named_Overrides__).
  568. For convenience [macroref BOOST_CONTRACT_OVERRIDES] can be used with multiple function names instead of repeating [macroref BOOST_CONTRACT_OVERRIDE] for each function name (on compilers that support variadic macros).
  569. For example, for three functions named `f`, `g`, and `h` (but same for any other number of functions), the following:
  570. BOOST_CONTRACT_OVERRIDES(f, g, h)
  571. Is equivalent to:
  572. [footnote
  573. There is no equivalent of [macroref BOOST_CONTRACT_NAMED_OVERRIDE] that operates on multiple function names at once ([macroref BOOST_CONTRACT_NAMED_OVERRIDE] is not expected to be used often so it can simply be repeated multiple times when needed).
  574. ]
  575. BOOST_CONTRACT_OVERRIDE(f)
  576. BOOST_CONTRACT_OVERRIDE(g)
  577. BOOST_CONTRACT_OVERRIDE(h)
  578. Public function overrides must always list the extra trailing parameter of type [classref boost::contract::virtual_]`*` with default value `0` (i.e., `nullptr`), even when they are not declared `virtual`, if this parameter is present in the signature of the virtual function being overridden from base classes.
  579. Programmers must pass the extra virtual parameter as the very first argument to all [macroref BOOST_CONTRACT_OLDOF] and [funcref boost::contract::public_function] calls in the public function override definition (see __Virtual_Public_Functions__).
  580. When called from public function overrides, the [funcref boost::contract::public_function] function takes a pointer to the enclosing function, the object `*this` (because public function overrides check class invariants, see __Class_Invariants__), and references to each function argument in the order they appear in the function declaration.
  581. [footnote
  582. *Rationale:*
  583. The object `this` is passed after the function pointer to follow `std::bind`'s syntax.
  584. The function pointer and references to all function arguments are needed for public function overrides because this library has to internally call overridden virtual public functions to check their contracts for subcontracting (even if this library will not actually execute the bodies of the overridden functions).
  585. ]
  586. For public function overrides returning `void`:
  587. class u {
  588. public:
  589. // A void public function override.
  590. void f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) /* override */ {
  591. boost::contract::check c = boost::contract::public_function<override_f>(
  592. v, &u::f, this, a_1, ..., a_n) // No result parameter...
  593. .precondition([&] { ... })
  594. .postcondition([&] { ... }) // ...so nullary functor.
  595. .except([&] { ... })
  596. ;
  597. ...
  598. }
  599. BOOST_CONTRACT_OVERRIDE(f)
  600. ...
  601. }
  602. For public function overrides not returning `void`, programmers must also pass a reference to the function return value as the second argument to [funcref boost::contract::public_function] (this library will generate a compile-time error otherwise).
  603. [footnote
  604. *Rationale:*
  605. As for non-overriding virtual public functions, also public function overrides use the extra return value parameter to pass it to the overridden functions when subcontracting.
  606. In the case of public function overrides, this library has the function pointer so it will generate a compile-time error if the function is non-void and programmers forget to specify the extra return value parameter (this extra error checking is not possible instead for non-overriding virtual public functions because their contracts do not take the function pointer as a parameter, see __Virtual_Public_Functions__).
  607. ]
  608. In this case, the library will pass this return value reference to the postcondition functor that must therefore take one single argument matching the return type, otherwise this library will generate a compile-time error (the functor parameter can be a constant reference `const&` to avoid extra copies of the return value, similarly to non-overriding non-void __Virtual_Public_Functions__):
  609. class u {
  610. public:
  611. // A non-void public function override.
  612. t f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) /* override */ {
  613. t result;
  614. boost::contract::check c = boost::contract::public_function<override_f>(
  615. v, result, &u::f, this, a_1, ..., a_n) // Result parameter...
  616. .precondition([&] { ... })
  617. .postcondition([&] (t const& result) { ... }) // ...so unary functor.
  618. .except([&] { ... })
  619. ;
  620. ... // Assign `result` at each return.
  621. }
  622. BOOST_CONTRACT_OVERRIDE(f)
  623. ...
  624. }
  625. This library will throw [classref boost::contract::bad_virtual_result_cast] if programmers specify return values for public function overrides in derived classes that are not consistent with the return types of the virtual public functions being overridden in the base classes.
  626. [footnote
  627. *Rationale:*
  628. The `boost::bad_any_cast` exception was not used here because it does not print the from- and to- type names (so it is not descriptive enough).
  629. ]
  630. [important
  631. It is the responsibility of the programmers to pass the extra virtual parameter `v` to all [macroref BOOST_CONTRACT_OLDOF] and [funcref boost::contract::public_function] calls within public function overrides, and also to pass the return value reference after `v` to [funcref boost::contract::public_function] for non-void public function overrides.
  632. This library cannot always generate compile-time errors if programmers fail to do so (but in general this will prevent the library from correctly checking contracts at run-time).
  633. *Mnemonics:*
  634. [:When `override_...` is present, always pass it as template parameter to [funcref boost::contract::public_function].]
  635. [:When `v` is present, always pass it as the first argument to [funcref boost::contract::public_function] and [macroref BOOST_CONTRACT_OLDOF].]
  636. [:Always pass `result` to [funcref boost::contract::public_function] right after `v` for non-void functions.]
  637. ]
  638. At construction, the [classref boost::contract::check] RAII object for public function overrides does the following (enclosing public function override entry):
  639. # Check static and non-static class invariants for all overridden bases and for the derived class in __AND__ with each other, by calling [^['type-of](['overridden-base_1])]`::static_invariant()` __AND__ [^['overridden-base_1]]`.invariant()` __AND__... [^['type-of](['overridden-base_n])]`::static_invariant()` __AND__ [^['overridden-base_n]]`.invariant()` __AND__ [^['type-of]]`(*this)::static_invariant()` __AND__ `this->invariant()`.
  640. # Check preconditions for all overridden base functions and for the overriding derived function in __OR__ with each other, by calling the nullary functors [^['r_1]]`()` __OR__... [^['r_n]]`()` __OR__ [^['r]]`()` passed to `.precondition(`[^['r_1]]`)`, ... `.precondition(`[^['r_n]]`)`, `.precondition(`[^['r]]`)` for all of the overridden and overriding functions respectively.
  641. At destruction instead (enclosing public function override exit):
  642. # Check static and non-static class invariants for all overridden bases and for the derived class in __AND__ with each other, by calling [^['type-of](['overridden-base_1])]`::static_invariant()` __AND__ [^['overridden-base_1]]`.invariant()` __AND__... [^['type-of](['overridden-base_n])]`::static_invariant()` __AND__ [^['overridden-base_n]]`.invariant()` __AND__ [^['type-of]]`(*this)::static_invariant()` __AND__ `this->invariant()` (even if the function body threw an exception).
  643. # If the function body did not throw an exception:
  644. # Check postconditions for all overridden base functions and for the overriding derived function in __AND__ with each other, by calling the nullary functors [^['s_1]]`()` __AND__... [^['s_n]]`()` __AND__ [^['s]]`()` passed to `.postcondition(`[^['s_1]]`)`, ... `.postcondition(`[^['s_n]]`)`, `.postcondition(`[^['s]]`)` for all of the overridden and overriding functions respectively (or the unary functors [^['s_1]]`(`[^['result]]`)` __AND__... [^['s_n]]`(`[^['result]]`)` __AND__ [^['s]]`(`[^['result]]`)` for non-void public function overrides).
  645. # Else:
  646. # Check exception guarantees for all overridden base functions and for the overriding derived function in __AND__ with each other, by calling the nullary functors [^['e_1]]`()` __AND__... [^['e_n]]`()` __AND__ [^['e]]`()` passed to `.except(`[^['e_1]]`)`, ... `.except(`[^['e_n]]`)`, `.except(`[^['e]]`)` for all of the overridden and overriding functions respectively.
  647. This ensures that contracts and subcontracts of public function overrides are correctly checked at run-time in accordance with the __substitution_principle__ (see __Public_Function_Calls__).
  648. For the rest, considerations made in __Virtual_Public_Functions__ apply to public function overrides as well.
  649. [note
  650. A public function override should always call [funcref boost::contract::public_function] (even if it has no preconditions, no postconditions, no exception guarantees, and its class has no invariants), otherwise this library will not be able to correctly use it for subcontracting.
  651. ]
  652. [endsect]
  653. [section Base Classes (Subcontracting)]
  654. In order for this library to support subcontracting, programmers must specify the bases of a derived class declaring a public member type named `base_types` via a `typedef` using [macroref BOOST_CONTRACT_BASE_TYPES].
  655. For example (see [@../../example/features/base_types.cpp =base_types.cpp=]):
  656. [import ../example/features/base_types.cpp]
  657. [base_types]
  658. For convenience, a /local macro/ named `BASES` can be used to avoid repeating the base list twice (first in the derived class declaration `class `[^['class-name]]` : `[^['base-list]] and then again when invoking `BOOST_CONTRACT_BASE_TYPES(`[^['base-list]]`)`).
  659. Being a local macro, `BASES` must be undefined using `#undef BASES` after it is used to declare the `base_types` `typedef` (to avoid name clashes and macro redefinition errors).
  660. [footnote
  661. The name of this local macro is arbitrary, but `BASES` is often used in this documentation.
  662. ]
  663. [macroref BOOST_CONTRACT_BASE_TYPES] is a variadic macro and accepts a list of bases separated by commas (see __No_Macros__ to program `base_types` without using macros).
  664. As already noted in __Constructors__, when the extra base [classref boost::contract::constructor_precondition] is used to program constructor preconditions, its inheritance access level must always be `private` and it must be specified as the very first base.
  665. [important
  666. Each base passed to [macroref BOOST_CONTRACT_BASE_TYPES] must /explicitly/ specify its inheritance access level `public`, `protected`, or `private` (but `virtual` is optional and can be specified either before or after the access level as usual in C++).
  667. This library will generate a compile-time error if the first base is missing its inheritance access level, but this library will not be able to always generate an error if the access level is missing for bases after the first one.
  668. [footnote
  669. *Rationale:*
  670. This library explicitly requires the inheritance access level because derived classes must subcontract only from public bases, but not from protected or private bases (see __Public_Function_Calls__).
  671. [macroref BOOST_CONTRACT_BASE_TYPES] inspects each inheritance access level using preprocessor meta-programming and removes non-public bases from the list of bases internally used for subcontracting.
  672. However, this library cannot always detect when programmers forget to specify the inheritance access level because, when commas are used to separate template parameters passed to base classes, the preprocessor will not be able to correctly use commas to identify the next base class token in the inheritance list (the preprocessor cannot distinguish between commas that are not protected by round parenthesis, like the ones used in templates).
  673. Therefore, this library uses the inheritance access level keyword `public`, `protected`, or `private` instead of commas `,` for the preprocessor to correctly find the next base class token in the inheritance list (thus inheritance access levels must always be explicit specified by programmers for each base).
  674. ]
  675. It is the responsibility of the programmers to make sure that all bases passed to [macroref BOOST_CONTRACT_BASE_TYPES] explicitly specify their inheritance access level (inheritance access levels are instead optional in C++ because `private` is implicitly assumed for `class` types and `public` for `struct` types).
  676. *Mnemonics:*
  677. [:Always explicitly specify the inheritance access level `public`, `protected`, or `private` for base classes passed to [macroref BOOST_CONTRACT_BASE_TYPES].]
  678. ]
  679. See __Access_Specifiers__ to avoid making the `base_types` member type `public`.
  680. [footnote
  681. In this documentation the `base_type` member type is often declared `public` for simplicity.
  682. However, in production code it might not be acceptable to augment the public members of a class adding the `base_types` type (and that can be avoided using [classref boost::contract::access] as explained in __Access_Specifiers__).
  683. ]
  684. See [macroref BOOST_CONTRACT_BASES_TYPEDEF] to use a name different from `base_types` (e.g., because `base_types` clashes with other names in user-defined classes).
  685. [endsect]
  686. [section Static Public Functions]
  687. Contracts for public functions are programmed using [funcref boost::contract::public_function].
  688. In this section, let's consider static public functions.
  689. For example (see [@../../example/features/static_public.cpp =static_public.cpp=]):
  690. [import ../example/features/static_public.cpp]
  691. [static_public]
  692. It is possible to specify preconditions, postconditions, and exception guarantees for static public functions (see __Preconditions__, __Postconditions__, and __Exception_Guarantees__).
  693. When called from static public functions, [funcref boost::contract::public_function] cannot take the object `this` as a parameter (because there is no object `this` in static member functions) so the enclosing class type is specified via an explicit template parameter as in [funcref boost::contract::public_function][^<['class-type]>] (the class type is required to check static class invariants, see __Class_Invariants__):
  694. class u {
  695. public:
  696. // A static public function.
  697. static void f() {
  698. boost::contract::check c = boost::contract::public_function<u>() // Class type `u` as explicit template parameter.
  699. .precondition([&] { ... })
  700. .postcondition([&] { ... })
  701. .except([&] { ... })
  702. ;
  703. ...
  704. }
  705. ...
  706. };
  707. The [funcref boost::contract::public_function] function returns an RAII object that must be assigned to a local variable of type [classref boost::contract::check] (otherwise this library will generate a run-time error, see [macroref BOOST_CONTRACT_ON_MISSING_CHECK_DECL]).
  708. Furthermore, C++11 `auto` declarations cannot be used here and the [classref boost::contract::check] type must be explicitly specified (otherwise this library will generate a compile-time error prior C++17 and a run-time error post C++17).
  709. The static public functions body is programmed right after the declaration of this RAII object.
  710. At construction, the [classref boost::contract::check] RAII object for static public functions does the following (enclosing static public function entry):
  711. # Check static class invariants, by calling [^['class-type]]`::static_invariant()` (but never non-static class invariants).
  712. # Check preconditions, by calling the nullary functor [^['r]]`()` passed to `.precondition(`[^['r]]`)`.
  713. At destruction instead (enclosing static public function exit):
  714. # Check static class invariants, by calling [^['class-type]]`::static_invariant()` (even if the function body threw an exception, but never non-static class invariants).
  715. # If the function body did not throw an exception:
  716. # Check postconditions, by calling the nullary functor [^['s]]`()` passed to `.postcondition(`[^['s]]`)`.
  717. # Else:
  718. # Check exception guarantees, by calling the nullary functor [^['e]]`()` passed to `.except(`[^['e]]`)`.
  719. This ensures that static public function contracts are correctly checked at run-time (static public functions do not subcontract because they have no object `this` and therefore there is no inheritance, see __Public_Function_Calls__).
  720. [note
  721. A static public function can avoid calling [funcref boost::contract::public_function] for efficiency but only when it has no preconditions, no postconditions, no exception guarantees, and its class has no static invariants (the class can still have non-static invariants or base classes instead).
  722. ]
  723. [endsect]
  724. [endsect]