Boost.Contract 1.0.0
Our field needs more formality, but the profession has not realized it yet.
-- Bertrand Meyer (see [Meyer97] page 400)
This library implements contract programming (a.k.a., Design by Contract or DbC) [1] for the C++ programming language. All contract programming features are supported by this library: Subcontracting, class invariants (also for static and volatile member functions), postconditions (with old and return values), preconditions, customizable actions on assertion failure (e.g., terminate the program or throw exceptions), optional compilation of assertions, disable assertions while already checking other assertions (to avoid infinite recursion), and more (see Feature Summary).
[1] Design by Contract (DbC) is a registered trademark of the Eiffel Software company and it was first introduced by the Eiffel programming language (see [Meyer97]).

Introduction
Contract programming allows to specify preconditions, postconditions, and class invariants that are automatically checked when functions are executed at run-time. These conditions assert program specifications within the source code itself allowing to find bugs more quickly during testing, making the code self-documenting, and increasing overall software quality (see Contract Programming Overview).
For example, consider the following function inc that increments its argument x by 1 and let's write its contract using code comments (see introduction_comments.cpp):

void inc(int& x)
    // Precondition:    x < std::numeric_limit<int>::max()
    // Postcondition:   x == oldof(x) + 1
{
    ++x; // Function body.
}

The precondition states that at function entry the argument x must be strictly smaller than the maximum allowable value of its type (so it can be incremented by 1 without overflowing). The postcondition states that at function exit the argument x must be incremented by 1 with respect to the old value that x had before executing the function (indicated here by oldof(x)). Note that postconditions shall be checked only when the execution of the function body did not throw an exception.
Now let's program this function and its contract using this library (see introduction.cpp and Non-Member Functions):

#include <boost/contract.hpp>

void inc(int& x) {
    boost::contract::old_ptr<int> old_x = BOOST_CONTRACT_OLDOF(x); // Old value.
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(x < std::numeric_limits<int>::max()); // Line 17.
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(x == *old_x + 1); // Line 20.
        })
    ;

    ++x; // Function body.
}

When the above function inc is called, this library will:
First, execute the functor passed to .precondition(...) that asserts inc precondition.
Then, execute inc body (i.e., all the code that follows the boost::contract::check c = ... declaration).
Last, execute the functor passed to .postcondition(...) that asserts inc postcondition (unless inc body threw an exception).
For example, if there is a bug in the code calling inc so that the function is called with x equal to std::numeric_limits<int>::max() then the program will terminate with an error message similar to the following (and it will be evident that the bug is in the calling code):

precondition assertion "x < std::numeric_limits<int>::max()" failed: file "introduction.cpp", line 17

Instead, if there is a bug in the implementation of inc so that x is not incremented by 1 after the execution of the function body then the program will terminate with an error message similar to the following (and it will be evident that the bug is in inc body): [2]
[2] In this example the function body is composed of a single trivial instruction ++x so it easy to check by visual inspection that it does not contain any bug and it will always increment x by 1 thus the function postcondition will never fail. In real code, function bodies are rarely this simple and can hide bugs which makes checking postconditions useful.

postcondition assertion "x == *old_x + 1" failed: file "introduction.cpp", line 20

By default, when an assertion fails this library prints an error message such the ones above to the standard error std::cerr and terminates the program calling std::terminate (this behaviour can be customized to take any user-specified action including throwing exceptions, see Throw on Failures). Note that the error messages printed by this library contain all the information necessary to easily and uniquely identify the point in the code at which contract assertions fail. [3]
[3] Rationale: The assertion failure message printed by this library follows a format similar to the message printed by Clang when the C-style assert macro fails.
C++11 lambda functions are necessary to use this library without manually writing a significant amount of boiler-plate code to program the functors that assert the contracts (see No Lambda Functions). That said, this library implementation does not use C++11 features and should work on most modern C++ compilers (see Getting Started).
In addition to contracts for non-member functions as shown the in the example above, this library allows to program contracts for constructors, destructors, and member functions. These can check class invariants and can also subcontract inheriting and extending contracts from base classes (see introduction_public.cpp and Public Function Overrides): [4]
[4] The pushable base class is used in this example just to show subcontracting, it is somewhat arbitrary and it will likely not appear in real code.

template<typename T>
class vector
    #define BASES public pushable<T>
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types; // For subcontracting.
    #undef BASES

    void invariant() const { // Checked in AND with base class invariants.
        BOOST_CONTRACT_ASSERT(size() <= capacity());
    }

    virtual void push_back(T const& value,
            boost::contract::virtual_* v = 0) /* override */ { // For virtuals.
        boost::contract::old_ptr<unsigned> old_size =
                BOOST_CONTRACT_OLDOF(v, size()); // Old values for virtuals.
        boost::contract::check c = boost::contract::public_function< // For overrides.
                override_push_back>(v, &vector::push_back, this, value)
            .precondition([&] { // Checked in OR with base preconditions.
                BOOST_CONTRACT_ASSERT(size() < max_size());
            })
            .postcondition([&] { // Checked in AND with base postconditions.
                BOOST_CONTRACT_ASSERT(size() == *old_size + 1);
            })
        ;

        vect_.push_back(value);
    }
    BOOST_CONTRACT_OVERRIDE(push_back) // Define `override_push_back` above.

    // Could program contracts for those as well.
    unsigned size() const { return vect_.size(); }
    unsigned max_size() const { return vect_.max_size(); }
    unsigned capacity() const { return vect_.capacity(); }

private:
    std::vector<T> vect_;
};

Language Support
The authors of this library advocate for contracts to be added to the core language. Adding contract programming to the C++ standard has a number of advantages over any library implementation (shorter and more concise syntax to program contracts, specify contracts in declarations instead of definitions, enforce contract constant-correctness, expected faster compile- and run-time, vendors could develop static analysis tools to recognize and check contracts statically when possible, compiler optimizations could be improved based on contract conditions, etc.).
Unfortunately, detailed and complete proposals to add contracts to the C++ standard such as [N1962] were rejected by the C++ standard committee and it is not clear if the current proposal for adding contracts to C++ [P0380] will actually be accepted by the standard. [5] In any case, at least for now [P0380] only supports pre- and postconditions while missing basic features such as class invariants and old values in postconditions, not to mention the lack of more advanced features like subcontracting. All these features are instead supported by this library (see Feature Summary for a detailed comparison between the features supported by this library and the ones listed in different contract programming proposals, see Bibliography for a list of references considered during the design and implementation of this library, including the vast majority of contract programming proposals submitted to the C++ standard committee).
[5] The authors find attractive the syntax that uses C++11 attributes [[...]] to specify contracts as indicated in [P0380].

Full Table of Contents

Introduction
Full Table of Contents
Getting Started
    This Documentation
    Compilers and Platforms
    Code Organization
Contract Programming Overview
    Assertions
    Benefits and Costs
    Function Calls
    Public Function Calls
    Constructor Calls
    Destructor Calls
    Constant-Correctness
    Specifications vs. Implementation
    On Contract Failures
    Feature Summary
Tutorial
    Non-Member Functions
    Preconditions
    Postconditions
    Return Values
    Old Values
    Exception Guarantees
    Class Invariants
    Constructors
    Destructors
    Public Functions
    Virtual Public Functions
    Public Function Overrides (Subcontracting)
    Base Classes (Subcontracting)
    Static Public Functions
Advanced
    Pure Virtual Public Functions
    Optional Return Values
    Private and Protected Functions
    Friend Functions
    Function Overloads
    Lambdas, Loops, Code Blocks (and constexpr)
    Implementation Checks
    Old Value Copies at Body
    Named Overrides
    Access Specifiers
    Throw on Failures (and noexcept)
Extras
    Old Value Requirements (Templates)
    Assertion Requirements (Templates)
    Volatile Public Functions
    Move Operations
    Unions
    Assertion Levels
    Disable Contract Checking
    Disable Contract Compilation (Macro Interface)
    Separate Body Implementation
    No Lambda Functions (No C++11)
    No Macros (and No Variadic Macros)
Examples
Reference
Release Notes
Bibliography
Acknowledgments

Getting Started
This section presents preliminary information to start using this library.

This Documentation
Programmers should be able to start using this library after reading the Introduction, Getting Started, and Tutorial. Other sections of this documentation (e.g., Advanced and Extras) can be consulted at a later point to gain a more in-depth knowledge of the library. Contract Programming Overview can be skipped by programmers that are already familiar with the contract programming methodology.
Some of the source code listed in this documentation contains special code comments of the form //[... and //]. These mark sections of the code that are automatically extracted from the source code and presented as part of this documentation. [6] It should be noted that the purpose of all examples of this documentation is to illustrate how to use this library and not to represent real product code.
[6] Rationale: This allows to make sure that most of the example code presented in this documentation is always up-to-date, builds and runs with the latest implementation of the library.
Some footnotes are marked by the word "Rationale". These explain some of the decisions made during the design and implementation of this library.

Compilers and Platforms
In general, this library requires C++ compilers with a sound implementation of SFINAE and other template meta-programming techniques supported by the C++03 standard. It is possible to use this library without C++11 lambda functions but a large amount of boiler-plate code is required to manually program separate functor to specify preconditions, postconditions, etc. (so using this library without C++11 lambda functions is possible but not recommended, see No Lambda Functions). It is also possible to use this library without variadic macros by manually programming a small amount of boiler-plate code (but most if not all modern C++ compilers support variadic macros even before C++99 and C++11 so this should never be needed in practice, see No Macros).
Some parts of this documentation use the syntax type-of(...) to indicate an operator logically equivalent to C++11 decltype(...). However, this library implementation does not actually use type deduction in these cases (because the library already knows the types in question) so support for C++11 decltype and other type-of implementations are not actually required by this library (that is why type-of and not the real decltype operator is used in this documentation).
This library has been developed and tested using:
Visual Studio 2015 on Windows (MSVC cl version 19.00.24215.1).
GCC version 5.4.0 on Cygwin (with C++11 features enabled -std=c++11).
Clang version 3.8.1 on Cygwin (with C++11 features enabled -std=c++11).
For information on other compilers and platforms see the library regression tests.
It is strongly recommended to compile and use this library as a shared library (a.k.a., Dynamically Linked Library or DLL) by defining the BOOST_ALL_DYN_LINK macro (or at least BOOST_CONTRACT_DYN_LINK) when building Boost.
It is possible to compile and use this library as a static library (by defining the BOOST_CONTRACT_STATIC_LINK macro) or as a header-only library (by leaving both BOOST_CONTRACT_DYN_LINK and BOOST_CONTRACT_STATIC_LINK undefined, as by default). However, this library is not guaranteed to always work correctly in these cases. Specifically, this library might not correctly disable contracts while checking other contracts and call the correct user-defined contract failure handlers unless it is compiled as a shared library when it is used across different program units (different programs, different shared libraries in the same program, etc.).

Code Organization
All headers required by this library can be included at once by:

#include <boost/contract.hpp>

Or, by the following when using the library macro interface (see Disable Contract Compilation):

#include <boost/contract_macro.hpp>

Alternatively, all boost/contract/*.hpp headers are independent from one another and they can be selectively included one-by-one based on the specific functionality of this library being used (but this was measured to not make an appreciable difference in compile-time so boost/contract.hp can be included directly in most cases). The boost/contract/core/*.hpp headers are not independent from other headers and they do not need to be directly included in user code when boost/contract.hpp or boost/contract/*.hpp headers are included already.
All files under boost/contract/detail/, names in the boost::contract::detail namespace, macros starting with BOOST_CONTRACT_DETAIL..., and all names starting with boost_contract_detail... (in any namespace, including user-defined namespaces) are part of this library implementation and should never be used directly in user code. Names starting with BOOST_CONTRACT_ERROR... are used by this library to report some compile-time errors (so spotting these names in compiler error messages might help troubleshooting).

Contract Programming Overview
It is absurd to make elaborate security checks on debugging runs, when no trust is put in the results, and then remove them in production runs, when an erroneous result could be expensive or disastrous. What would we think of a sailing enthusiast who wears his life-jacket when training on dry land but takes it off as soon as he goes to sea?
-- Charles Antony Richard Hoare (see [Hoare73])
This section gives an overview of contract programming (see [Meyer97], [Mitchell02], and [N1613] for more detailed introductions to contract programming). Readers that already have a basic understanding of contract programming can skip this section and maybe come back to it after reading the Tutorial.
The objective of this library is not to convince programmers to use contract programming. It is assumed that programmes understand the benefits and trade-offs associated with contract programming and they have already decided to use this methodology in their code. Then, this library aims to be the best and more complete contract programming library for C++ (without using preprocessors and other tools external to the C++ preprocessor and language itself).

Assertions
Contract programming is characterized by the following assertion mechanisms:
Preconditions: These are logical conditions that programmers expect to be true when a function is called (e.g., to check constraints on function arguments). Operations that logically have no preconditions (i.e., that are always well-defined for the entire domain of their inputs) are often referred to as having a wide contract. This is in contrast to operations that have preconditions which are often referred to as having a narrow contract (note that operations with truly narrow contracts are expected to also never throw exceptions). [7]
[7] The nomenclature of wide and narrow contracts has gained some popularity in recent years in the C++ community (appearing in a number of more recent proposals to add contract programming to the C++ standard, see Bibliography). This nomenclature is perfectly reasonable but it is not often used in this document just because the authors generally prefer to explicitly mention "this operation has no preconditions..." or "this operation has preconditions...".
Postconditions: These are logical conditions that programmers expect to be true when a function exits without throwing an exception (e.g., to check the result and any side effect that a function might have). Postconditions can access the function return value (for non-void functions) and also old values (which are the values that expressions had before the function body was executed).
Exception guarantees: These are logical conditions that programmers except to be true when a function exits throwing an exception. Exception guarantees can access old values (but not the function return value). [8]
[8] Rationale: Contract assertions for exception guarantees were first introduced by this library (even if exception safety guarantees have long been part of C++ STL documentation). Contract assertions for exception safety guarantees are not part of [N1962] or other references listed in the Bibliography.
Class invariants: These are logical conditions that programmers expect to be true after a constructor exits without throwing an exception, before and after the execution of every non-static public function (even if they throw exceptions), before the destructor is executed (and also after the destructor is executed but only when the destructor throws an exception). Class invariants define valid states for all objects of a given class. It is possible to specify a different set of class invariants for volatile public functions, namely volatile class invariants. It is also possible to specify static class invariants which are excepted to be true before and after the execution of any constructor, destructor (even if it does not throw an exception), and public function (even if static). [9]
[9] Rationale: Static and volatile class invariants were first introduced by this library to reflect the fact that C++ supports both static and volatile public functions. Static and volatile class invariants are not part of [N1962] or other references listed in the Bibliography.
Subcontracting: This indicates that preconditions cannot be strengthen, while postconditions and class invariants cannot be weaken when a public function in a derived class overrides public functions in one or more of its base classes (this is formally defined according to the substitution principle).
Class invariants can also be used to specify basic exception safety guarantees for an object (because they are checked at exit of public functions even when those throw exceptions), while contract assertions for exception guarantees can be used to specify strong exception safety guarantees for given operations on the same object.
It is also a common requirement for contract programming to automatically disable contract checking while already checking assertions from another contract (in order to avoid infinite recursion while checking contract assertions).
This library implements this requirement but in order to globally disable assertions while checking another assertion some kind of global arbitrating variable needs to be used by this library implementation. This library will automatically protect such a global variable from race conditions in multi-threated programs, but this will effectively introduce a global lock in the program (the BOOST_CONTRACT_DISABLE_THREADS macro can be defined to disable this global lock but at the risk of incurring in race conditions). [10]
[10] Rationale: BOOST_CONTRACT_DISABLE_THREADS is named after BOOST_DISABLE_THREADS.
In general, it is recommended to specify different contract conditions using separate assertion statements and not to group them together into a single condition using logical operators (&&, ||, etc.). This is because when contract conditions are programmed together in a single assertion using logical operators, it might not be clear which condition actually failed in case the entire assertion fails at run-time.

C-Style Assertions
A limited form of contract programming is the use of the C-style assert macro. Using assert is common practice for many programmers but it suffers of the following limitations:
assert does not distinguish between preconditions and postconditions. In well-tested production code, postconditions can usually be disabled trusting the correctness of the implementation while preconditions might still need to remain enabled because of possible changes in the calling code (e.g., postconditions of a given library could be disabled after testing while its preconditions can be kept enabled given the library cannot predict changes in the user code that will be calling the library). Using assert it is not possible to selectively disable only postconditions and all assertions must be disabled at once.
assert requires to manually program extra code to check class invariants (extra member functions, try blocks, etc.).
assert does not support subcontracting.
assert calls are usually scattered within function implementations thus the asserted conditions are not immediately visible in their entirety by programmers (as they are instead when the assertions appear in the function declaration or at least at the very top of the function definition).
Contract programming does not suffers of these limitations.

Benefits and Costs

Benefits
The main use of contract programming is to improve software quality. [Meyer97] discusses how contract programming can be used as the basic tool to write correct software. [Stroustrup94] discusses the key importance of class invariants plus advantages and disadvantages of preconditions and postconditions. The following is a short summary of benefits associated with contract programming inspired mainly by [N1613]:
Preconditions and postconditions: Using function preconditions and postconditions, programmers can give a precise semantic description of what a function requires at its entry and what it ensures at its exit (if it does not throw an exception). In particular, using postcondition old values, contract programming provides a mechanism that allows programmers to compare values of an expression before and after the function body execution. This mechanism is powerful enough to enable programmers to express many correctness constraints within the code itself, constraints that would otherwise have to be captured at best only informally by documentation.
Class invariants: Using class invariants, programmers can describe what to expect from a class and the logic dependencies between the class members. It is the job of the constructor to ensure that the class invariants are satisfied when the object is first created. Then the implementation of the member functions can be largely simplified as they can be written knowing that the class invariants are satisfied because contract programming checks them before and after the execution of every public function. Finally, the destructor makes sure that the class invariants held for the entire life of the object checking the class invariants one last time before the object is destructed. Class invariants can also be used as a criteria for good abstractions: If it is not possible to specify an invariant, it might be an indication that the design abstraction maybe be poor and it should not have been made into a class (maybe a namespace would have sufficed instead).
Self-documenting code: Contracts are part of the source code, they are checked at run-time so they are always up-to-date with the code itself. Therefore program specifications, as documented by the contracts, can be trusted to always be up-to-date with the implementation.
Easier debugging: Contract programming can provide a powerful debugging facility because, if contracts are well written, bugs will cause contract assertions to fail exactly where the problem first occurs instead than at some later stage of the program execution in an apparently unrelated (and often hard to debug) manner. Note that a precondition failure points to a bug in the function caller, a postcondition failure points instead to a bug in the function implementation. [11]
[11] Of course, if contracts are ill-written then contract programming is of little use. However, it is less likely to have a bug in both the function body and the contract than in the function body alone. For example, consider the validation of a result in postconditions. Validating the return value might seem redundant, but in this case we actually want that redundancy. When programmers write a function, there is a certain probability that they make a mistake in implementing the function body. When programmers specify the result of the function in the postconditions, there is also a certain probability that they make a mistake in writing the contract. However, the probability that programmers make a mistake twice (in both the body and the contract) is in general lower than the probability that the mistake is made only once (in either the body or the contract).
Easier testing: Contract programming facilitates testing because a contract naturally specifies what a test should check. For example, preconditions of a function state which inputs cause the function to fail and postconditions state which outputs are produced by the function on successful exit (contract programming should be seen as a tool to complement, but obviously not to replace, testing).
Formal design: Contract programming can serve to reduce the gap between designers and programmers by providing a precise and unambiguous specification language in terms of the contract assertions. Moreover, contracts can make code reviews easier by clarifying some of the semantics and usage of the code.
Formalized inheritance: Contract programming formalizes the virtual function overriding mechanism using subcontracting as justified by the substitution principle. This keeps the base class programmers in control as overriding functions always have to fully satisfy the contracts of their base classes.
Replace defensive programming: Contract programming assertions can replace defensive programming checks localizing these checks within the contracts and making the code more readable.
Of course, not all formal contract specifications can be asserted in C++. For example, in C++ is it not possible to assert the validity of an iterator range in the general case because the only way to check if two iterators form a valid range is to keep incrementing the first iterator until we reach the second iterator. However, in case the iterator range is invalid, such a code would render undefined behaviour or run forever instead of failing an assertion. Nevertheless, a large amount of contract assertions can be successfully programmed in C++ as illustrated by the numerous examples in this documentation and from the literature (for example see how much of STL vector contract assertions can actually be programmed in C++ using this library).

Costs
In general, contract programming benefits come at the cost of performance as discussed in detail by both [Stroustrup94] and [Meyer97]. While performance trade-offs should be carefully considered depending on the specific application domain, software quality cannot be sacrificed: It is difficult to see value in software that quickly and efficiently provides incorrect results.
The run-time performances are negatively impacted by contract programming mainly because of extra time require to:
Check the asserted conditions.
Copy old values when these are used in postconditions or exception guarantees.
Call additional functors that check preconditions, postconditions, exception guarantees, class invariants, etc. (especially for subcontracting).
In general, contracts introduce at least three extra functor calls to check preconditions, postconditions, and exception guarantees for any given non-member function call. Public functions introduce also two more function calls to check class invariants (at entry and at exit). For subcontracting, these extra calls (some of which become virtual calls) are repeated for the number of functions being overridden from the base classes (possibly deep in the inheritance tree). In addition to that, this library introduces a number of function calls internal to its implementation in order to properly check the contracts.
To mitigate the run-time performance impact, programmers can selectively disable run-time checking of some of the contract assertions. Programmers will have to decide based on the performance trade-offs required by their applications, but a reasonable approach often is to (see Disable Contract Checking):
Always write contracts to clarify the semantics of the design embedding the specifications directly in the code and making the code self-documenting.
Check preconditions, postconditions, class invariants, and maybe even exception guarantees during initial testing.
Check only preconditions (and maybe class invariants, but not postconditions and exception guarantees) during release testing and for the final release.
This approach is usually reasonable because in well-tested production code, validating the function body implementation using postconditions is rarely needed since the function has shown itself to be correct during testing. On the other hand, checking function arguments using preconditions is always needed because of changes that can be made to the calling code (without having to necessarily re-test and re-release the called code). Furthermore, postconditions and also exception guarantees, with related old value copies, are often computationally more expensive to check than preconditions and class invariants.

Function Calls

Non-Member Functions
A call to a non-member function with a contract executes the following steps (see boost::contract::function):
Check function preconditions.
Execute the function body.
If the body did not throw an exception, check function postconditions.
Else, check function exception guarantees.

Private and Protected Functions
Private and protected functions do not have to satisfy class invariants because these functions are part of the class implementation and not of the class public interface. Furthermore, the substitution principle does not apply to private and protected functions because these functions are not accessible to the user at the calling site where the substitution principle applies.
Therefore, calls to private and protected functions with contracts execute the same steps as the ones indicated above for non-member functions (checking only preconditions and postconditions, without checking class invariants and subcontracting).

Public Function Calls

Overriding Public Functions
Let's consider a public function in a derived class that overrides public virtual functions declared its public base classes (because of C++ multiple inheritance, the function could override from more than one of its base classes). We refer to the function in the derived class as the overriding function, and to the set of base classes containing all the overridden functions as overridden bases.
When subcontracting, overridden functions are searched (at compile-time) deeply in the public branches of the inheritance tree (i.e., not just the derived class's direct public parents are inspected, but also all its public grandparents, etc.). In case of multiple inheritance this search also extends widely to all multiple public base classes following their order of declaration in the derived class inheritance list (as usual in C++, this search could result in multiple overridden functions and therefore in subcontracting from multiple public base classes). Note that only public base classes are considered for subcontracting because private and protected base classes are not accessible to the user at the calling site where the substitution principle applies.
A call to the overriding public function with a contract executes the following steps (see boost::contract::public_function):
Check static class invariants AND non-static class invariants for all overridden bases, AND then check the derived class static AND non-static invariants.
Check preconditions of overridden public functions from all overridden bases in OR with each other, OR else check the overriding function preconditions in the derived class.
Execute the overriding function body.
Check static class invariants AND non-static class invariants for all overridden bases, AND then check the derived class static AND non-static invariants (even if the body threw an exception).
If the body did not throw an exception, check postconditions of overridden public functions from all overridden bases in AND with each other, AND then check the overriding function postconditions in the derived class.
Else, check exception guarantees of overridden public functions from all overridden bases in AND with each other, AND then check the overriding function exception guarantees in the derived class.
Volatile public functions check static class invariants AND volatile class invariants instead. Preconditions and postconditions of volatile public functions and volatile class invariants access the object as volatile.
Class invariants are checked before preconditions and postconditions so programming precondition and postcondition assertions can be simplified assuming that class invariants are satisfied already (e.g., if class invariants assert that a pointer cannot be null then preconditions and postconditions can safety dereference that pointer without additional checking). Similarly, static class invariants are checked before non-static class invariants so programming non-static class invariant (volatile and non) can be simplified assuming that static class invariants are satisfied already. Furthermore, subcontracting checks contracts of public base classes before checking the derived class contracts so programming derived class contract assertions can be simplified by assuming that public base class contracts are satisfied already.
In this documentation AND and OR indicate the logic and and or operations evaluated in short-circuit. For example: p AND q is true if and only if both p and q are true, but q is never evaluated when p is false; p OR q is true if and only if either p or q are true, but q is never evaluated when p is true.
As indicated by the steps above and in accordance with the substitution principle, subcontracting checks preconditions in OR while class invariants, postconditions, and exceptions guarantees in AND with preconditions, class invariants, postconditions, and exceptions guarantees of base classes.

Non-Overriding Public Functions
A call to a non-static public function with a contract (that does not override functions from any of the public base classes) executes the following steps (see boost::contract::public_function):
Check class static AND non-static invariants (but none of the invariants from base classes).
Check function preconditions (but none of the preconditions from functions in base classes).
Execute the function body.
Check the class static AND non-static invariants (even if the body threw an exception, but none of the invariants from base classes).
If the body did not throw an exception, check function postconditions (but none of the postconditions from functions in base classes).
Else, check function exception guarantees (but none of the exception guarantees from functions in base classes).
Volatile public functions check static class invariants AND volatile class invariants instead. Preconditions and postconditions of volatile functions and volatile class invariants access the object as volatile.
Class invariants are checked because this function is part of the class public interface. However, none of the contracts of the base classes are checked because this function does not override any functions from any of the public base classes (so the substitution principle does not require to subcontract in this case).

Static Public Functions
A call to a static public function with a contract executes the following steps (see boost::contract::public_function):
Check static class invariants (but not the non-static invariants and none of the invariants from base classes).
Check function preconditions (but none of the preconditions from function in base classes).
Execute the function body.
Check static class invariants (even if the body threw an exception, but not the non-static invariants and none of the invariants from base classes).
If the body did not throw an exception, check function postconditions (but none of the postconditions from functions in base classes).
Else, check function exception guarantees (but none of the exception guarantees from functions in base classes).
Class invariants are checked because this function is part of the class public interface, but only static class invariants can be checked (because this is a static function so it cannot access the object that would instead be required to check non-static class invariants, volatile or not). Furthermore, static functions cannot override any function so the substitution principle does not apply and they do not subcontract.
Preconditions and postconditions of static functions and static class invariants cannot access the object (because they are checked from static member functions).

Constructor Calls
A call to a constructor with a contract executes the following steps (see boost::contract::constructor_precondition and boost::contract::constructor):
Check constructor preconditions (but these cannot access the object because the object is not constructed yet).
Execute the constructor member initialization list (if present).
Construct any base class (public or not) according with C++ construction mechanism and also check the contracts of these base constructors (according with steps similar to the ones listed here).
Check static class invariants (but not the non-static or volatile class invariants, because the object is not constructed yet).
Execute the constructor body.
Check static class invariants (even if the body threw an exception).
If the body did not throw an exception:
Check non-static AND volatile class invariants (because the object is now successfully constructed).
Check constructor postconditions (but these cannot access the object old value oldof(*this) because there was no object before the execution of the constructor body).
Else, check constructor exception guarantees (but these cannot access the object old value oldof(*this) because there was no object before the execution of the constructor body, plus they can only access class static members because the object was not successfully constructed upon the constructor body throwing an exception).
Constructor preconditions are checked before executing the member initialization list so programming these initializations can be simplified assuming the constructor preconditions are satisfied (e.g., constructor arguments can be validated by the constructor preconditions before they are used to initialize base classes and data members).
As indicated in step 2.a. above, C++ object construction mechanism will automatically check base class contracts when these bases are initialized (no explicit subcontracting behaviour is required here).

Destructor Calls
A call to a destructor with a contract executes the following steps (see boost::contract::destructor):
Check static class invariants AND non-static AND volatile class invariants.
Execute the destructor body (destructors have no parameters and they can be called at any time after object construction so they have no preconditions).
Check static class invariants (even if the body threw an exception).
If the body did not throw an exception:
Check destructor postconditions (but these can only access class static members and the object old value oldof(*this) because there is no object after successful execution of the destructor body). [12]
[12] Rationale: Postconditions for destructors are not part of [N1962] or other references listed in the Bibliography (but with respect to [Meyer97] it should be noted that Eiffel does not support static data members and that might by why destructors do not have postconditions in Eiffel). However, in principle there could be uses for destructor postconditions so this library supports postconditions for destructors (e.g., a class that counts object instances could use destructor postconditions to assert that an instance counter stored in a static data member is decreased by 1 because the object has been destructed).
Destroy any base class (public or not) according with C++ destruction mechanism and also check the contracts of these base destructors (according with steps similar to the ones listed here).
Else (even if destructors should rarely, if ever, be allowed to throw exceptions in C++):
Check non-static class invariants (because the object was not successfully destructed so it still exists and should satisfy its invariants).
Check destructor exception guarantees.
As indicated in step 4.b. above, C++ object destruction mechanism will automatically check base class contracts when the destructor exits without throwing an exception (no explicit subcontracting behaviour is required here).
Given that C++ allows destructors to throw, this library handles the case when the destructor body throws an exception as indicated above. However, in order to comply with STL exception safety guarantees and good C++ programming practices, programmers should implement destructor bodies to rarely, if ever, throw exceptions (in fact destructors are implicitly declared noexcept in C++11).

Constant-Correctness
Contracts should not be allowed to modify the program state because they are only responsible to check (and not to change) the program state in order to verify its compliance with the specifications. Therefore, contracts should only access objects, function arguments, function return values, old values, and all other program variables in const context (via const&, const* const, const volatile, etc.).
Whenever possible (e.g., class invariants and postcondition old values), this library automatically enforces this constant-correctness constraint at compile-time using const. However, this library cannot automatically enforce this constraint in all cases (for preconditions and postconditions of mutable member functions, for global variables, etc.). See No Lambda Functions for ways of using this library that enforces the constant-correctness constraint at compile-time (but at the cost of significant boiler-plate code to be programmed manually so not recommended in general).
In general, it is the responsibility of the programmers to code assertions that only check, and do not change, program variables. [13]
[13] Note that this is true when using C-style assert as well.

Specifications vs. Implementation
Contracts are part of the program specifications and not of its implementation. Therefore, contracts should ideally be programmed within C++ declarations, and not within definitions.
In general, this library cannot satisfy this requirement. However, even when contracts are programmed together with the body in the function definition, it is still fairly easy for users to identify and read just the contract portion of the function definition (because the contract code must always be programmed at the very top of the function definition). See Separate Body Implementation for ways of using this library to program contract specifications outside of the body implementation (but at the cost of writing one extra function for any given function, for applications where this requirement is truly important).
Furthermore, contracts are most useful when they assert conditions only using public members (in most cases, the need for using non-public members to check contracts, especially in preconditions, indicates an error in the class design). For example, the caller of a public function cannot in general make sure that the function preconditions are satisfied if the precondition assertions use private members that are not callable by the caller (therefore, a failure in the preconditions will not necessarily indicate a bug in the caller given that the caller was made unable to fully check the preconditions in the first place). However, given that C++ provides programmers ways around access level restrictions (friend, function pointers, etc.), this library leaves it up to the programmers to make sure that only public members are used in contract assertions (especially in preconditions). ([N1962] follows the same approach not restricting contracts to only use public members, Eiffel instead generates a compile-time error if preconditions are asserted using non-public members.) [14]
[14] Rationale: If C++ defect 45 had not been fixed, this library could have been implemented to generate a compile-time error when precondition assertions use non-public members more similarly to Eiffel's implementation (but not necessary the best approach for C++).

On Contract Failures
If preconditions, postconditions, exception guarantees, or class invariants are either checked to be false or their evaluation throws an exception at run-time then this library will call specific failure handler functions.
By default, these failure handler functions print a message to the standard error std::cerr (with detailed information about the failure) and then terminate the program calling std::terminate. However, using boost::contract::set_precondition_failure, boost::contract::set_postcondition_failure, boost::contract::set_except_failure, boost::contract::set_invariant_failure, etc. programmers can define their own failure handler functions that can take any user-specified action (throw an exception, exit the program with an error code, etc., see Throw on Failures). [15]
[15] Rationale: This customizable failure handling mechanism is similar to the one used by C++ std::terminate and also to the one proposed in [N1962].
In C++ there are a number of issues with programming contract failure handlers that throw exceptions instead of terminating the program. Specifically, destructors check class invariants so they will throw if programmers change class invariant failure handlers to throw instead of terminating the program, but in general destructors should not throw in C++ (to comply with STL exception safety, C++11 implicit noexcept declarations for destructors, etc.). Furthermore, programming a failure handler that throws for exception guarantees will throw an exception (the one reporting the contract failure) while there is already an active exception (the one that caused the exception guarantees to be checked in the first place), and this will force C++ to terminate the program anyway.
Therefore, it is recommended to terminate the program at least for contract failures from destructors and exception guarantees (if not in all other cases of contract failures as it is done by default by this library). The contract failure handler functions programmed using this library have information about the failed contract (preconditions, postconditions, etc.) and the operation that was checking the contract (constructor, destructor, etc.) so programmers can granularly distinguish all cases and decide when it is appropriate to terminate, throw, or take some other user-specific action.

Feature Summary
The contract programming features supported by this library are largely based on [N1962] and on the Eiffel programming language. The following table compares contract programming features among this library, [N1962] (unfortunately the C++ standard committee rejected this proposal commenting on a lack of interest in adding contract programming to C++ at that time, even if [N1962] itself is sound), a more recent proposal [P0380] (which has gain some traction within the C++ standard committee but unfortunately only supports preconditions and postconditions, while does not support class invariants, old values, and subcontracting), the Eiffel and D programming languages:
Feature	This Library	[N1962] Proposal (not accepted in C++)	[P0380] Proposal (being considered for C++2x)	ISE Eiffel 5.4 (see [Meyer97])	D (see [Bright04])
Keywords and specifiers	Specifiers: precondition, postcondition, invariant, static_invariant, and base_types. The last three specifiers appear in user code so their names can be referred to or changed using BOOST_CONTRACT_INVARIANT, BOOST_CONTRACT_STATIC_INVARIANT, and BOOST_CONTRACT_BASES_TYPEDEF macros respectively to avoid name clashes.	Keywords: precondition, postcondition, oldof, and invariant.	Attributes: [[expects]] and [[ensures]].	Keywords: require, require else, ensure, ensure then, old, result, do, and invariant.	Keywords: in, out, do, assert, and invariant.
On contract failures	Print an error to std::cerr and call std::terminate (but can be customized to throw exceptions, exit with an error code, etc.).	Call std::terminate (but can be customized to throw exceptions, exit with an error code, etc.).	Call std::abort (but can be customized to throw exceptions, exit with an error code, etc.).	Throw exceptions.	Throw exceptions.
Return values in postconditions	Yes, captured by or passed as a parameter to (for virtual functions) the postcondition functor.	Yes, postcondition(result-variable-name).	Yes, [[ensures result-variable-name: ...]].	Yes, result keyword.	Yes, out(result-variable-name).
Old values in postconditions	Yes, BOOST_CONTRACT_OLDOF macro and boost::contract::old_ptr (but copied before preconditions unless .old(...) is used as shown in Old Value Copies at Body). For templates, boost::contract::old_ptr_if_copyable skips old value copies for non-copyable types and boost::contract::condition_if skips old value copies selectively based on old expression type requirements.	Yes, oldof keyword (copied right after preconditions). (Never skipped, not even in templates for non-copyable types.)	No.	Yes, old keyword (copied right after preconditions). (Never skipped, but all types are copyable in Eiffel.)	No.
Class invariants	Yes, checked at constructor exit, at destructor entry and throw, and at public function entry, exit, and throw. Same for volatile class invariants. Static class invariants checked at entry, exit, and throw for constructors, destructors, and any (also static) public function.	Yes, checked at constructor exit, at destructor entry and throw, and at public function entry, exit, and throw. (Volatile and static class invariants not supported.)	No.	Yes, checked at constructor exit, and around public functions. (Volatile and static class invariants do not apply to Eiffel.)	Yes, checked at constructor exit, at destructor entry, and around public functions. However, invariants cannot call public functions (to avoid infinite recursion because D does not disable contracts while checking other contracts). (Volatile and static class invariants not supported, volatile was deprecated all together in D.)
Subcontracting	Yes, also supports subcontracting for multiple inheritance (BOOST_CONTRACT_BASE_TYPES, BOOST_CONTRACT_OVERRIDE, and boost::contract::virtual_ are used for declaring base classes, overrides and virtual public functions respectively).	Yes, also supports subcontracting for multiple inheritance, but preconditions cannot be subcontracted. [16]	No.	Yes.	Yes.
[16] Rationale: The authors of [N1962] decided to forbid derived classes from subcontracting preconditions because they found that such a feature was rarely, if ever, used (see Re: [boost] [contract] diff n1962). Still, it should be noted that even in [N1962] if a derived class overrides two functions with preconditions coming from two different base classes via multiple inheritance, the overriding function contract will check preconditions from its two base class functions in OR (so even in [N1962] preconditions can indirectly subcontract when multiple inheritance is used). The authors of this library found that confusing about [N1962]. Furthermore, subcontracting preconditions is soundly defined by the substitution principle so this library allows to subcontract preconditions as Eiffel does (users can always avoid using this feature if they have no need for it). (This is essentially the only feature on which this library deliberately differ from [N1962].)
Contracts for pure virtual functions	Yes (programmed via out-of-line functions as always in C++ with pure virtual function definitions).	Yes.	No (because no subcontracting).	Yes (contracts for abstract functions).	No.
Arbitrary code in contracts	Yes (but users are generally recommended to only program assertions using BOOST_CONTRACT_ASSERT and if-guard statements within contracts to avoid introducing bugs and expensive code in contracts, and also to only use public functions to program preconditions).	No, assertions only (use of only public functions to program preconditions is recommended but not prescribed).	No, assertions only (in addition only public members can be used in preconditions).	No, assertions only (in addition only public members can be used in preconditions).	Yes.
Constant-correctness	No, enforced only for class invariants and old values (making also preconditions and postconditions constant-correct is possible but requires users to program a fare amount of boiler-plate code).	Yes.	Yes.	Yes.	No, enforced only for class invariants.
Contracts in specifications	No, in function definitions instead (unless programmers manually write an extra function for any given function).	Yes (in function declarations).	Yes (in function declarations).	Yes.	Yes.
Function code ordering	Preconditions, postconditions, exception guarantees, body.	Preconditions, postconditions, body.	Preconditions, postconditions, body.	Preconditions, body, postconditions.	Preconditions, postconditions, body.
Disable assertion checking within assertions checking (to avoid infinite recursion when checking contracts)	Yes, but use BOOST_CONTRACT_PRECONDITIONS_DISABLE_NO_ASSERTION to disable no assertion while checking preconditions (see BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION). [17] (In multi-threaded programs this introduces a global lock, see BOOST_CONTRACT_DISABLE_THREADS.)	Yes for class invariants and postconditions, but preconditions disable no assertion.	No.	Yes.	No.
[17] Rationale: Theoretically, it can be shown that an incorrect argument might be passed to the function body when assertion checking is disabled while checking preconditions (see Re: [boost] [contract] diff n1962). However, that possibility is limited to contract checking when an incorrect argument will simply fail the contract and call the related contract failure handler as expected anyway. In any case, because of that [N1962] does not disable any assertion while checking preconditions. That makes it possible to have infinite recursion while checking preconditions so Eiffel disables assertion checking also while checking preconditions. Therefore, this library by default disables assertion checking also while checking preconditions, but it also provides the BOOST_CONTRACT_PRECONDITIONS_DISABLE_NO_ASSERTION configuration macro so users can change this behaviour to match [N1962] if needed.
Nested member function calls	Disable nothing. [18]	Disable nothing.	Disable nothing.	Disable all contract assertions.	Disable nothing.
[18] Rationale: Older versions of this library defined a data member in the user class that was automatically used to disable checking of class invariants within nested member function calls (similarly to Eiffel). This feature was required by older revisions of [N1962] but it is no longer required in [N1962] (because it seems to be motivated purely by optimization reasons while similar performances can be achieved by disabling invariants for release builds). Furthermore, in multi-threaded programs this feature would introduce a lock that synchronizes all member functions calls for a given object. Therefore, this feature was removed in the current revision of this library.
Disable contract checking	Yes, contract checking can be skipped at run-time by defining combinations of the BOOST_CONTRACT_NO_PRECONDITIONS, BOOST_CONTRACT_NO_POSTCONDITIONS, BOOST_CONTRACT_NO_INVARIANTS, BOOST_CONTRACT_NO_ENTRY_INVARIANTS, and BOOST_CONTRACT_NO_EXIT_INVARIANTS macros (completely removing contract code from compiled object code is possible but requires using macros shown in Disable Contract Compilation).	Yes (contract code also removed from compiled object code, but details are compiler-implementation specific).	Yes (contract code also removed from compiled object code, but details are compiler-implementation specific).	Yes, but only predefined combinations of preconditions, postconditions, and class invariants can be disabled (contract code also removed from compiled object code).	Yes.
Assertion levels	Yes, predefined default, audit, and axiom, in addition programmers can also define their own levels.	No (but a previous revision of this proposal considered adding assertion levels under the name of "assertion ordering").	Yes, predefined default, audit, and axiom.	No.	No.
The authors of this library consulted the following references that implement contract programming for C++ (but usually for only a limited set of features, or using preprocessing tools other than the C++ preprocessor and external to the language itself) and for other languages (see Bibliography for a complete list of all the references consulted during the design and development of this library):
Reference	Language	Notes
[Bright04b]	Digital Mars C++	The Digital Mars C++ compiler extends C++ adding contract programming language support (among many other features).
[Maley99]	C++	This supports contract programming including subcontracting but with limitations (e.g., programmers need to manually build an inheritance tree using artificial template parameters), it does not use macros but programmers are required to write by hand a significant amount of boiler-plate code. (The authors have found this work very inspiring when developing initial revisions of this library especially for its attempt to support subcontracting.)
[Lindrud04]	C++	This supports class invariants and old values but it does not support subcontracting (contracts are specified within definitions instead of declarations and assertions are not constant-correct).
[Tandin04]	C++	Interestingly, these contract macros automatically generate Doxygen documentation [19] but old values, class invariants, and subcontracting are not supported (plus contracts are specified within definitions instead of declarations and assertions are not constant-correct).
[19] Rationale: Older versions of this library also automatically generated Doxygen documentation from contract definition macros. This functionality was abandoned for a number of reasons: This library no longer uses macros to program contracts; even before that, the implementation of this library macros became too complex and the Doxygen preprocessor was no longer able to expand them; the Doxygen documentation was just a repeat of the contract code (so programmers could directly look at contracts in the source code); Doxygen might not necessarily be the documentation tool used by all C++ programmers.
[Nana]	GCC C++	This uses macros but it only works on GCC (and maybe Clang, but it does not work on MSVC, etc.). It does not support subcontracting. It requires extra care to program postconditions for functions with multiple return statements. It seems that it might not check class invariants when functions throw exceptions (unless the END macro does that...). (In addition, it provides tools for logging and integration with GDB.)
[C2]	C++	This uses an external preprocessing tool (the authors could no longer find this project's code to evaluate it).
[iContract]	Java	This uses an external preprocessing tool.
[Jcontract]	Java	This uses an external preprocessing tool.
[CodeContracts]	.NET	Microsoft contract programming for .NET programming languages.
[SpecSharp]	C#	This is a C# extension with contract programming language support.
[Chrome]	Object Pascal	This is the .NET version of Object Pascal and it has language support for contract programming.
[SPARKAda]	Ada	This is an Ada-like programming language with support for contract programming.
To the best knowledge of the authors, this the only library that fully supports all contract programming features for C++ (without using preprocessing tools external to the language itself):
Implementing preconditions and postconditions in C++ is not difficult (e.g., using some kind of RAII object).
Implementing postcondition old values is also not too difficult usually requiring programmers to copy old values into local variables, but it is already somewhat more difficult to ensure such copies are not performed when postconditions are disabled. [20]
[20] For example, the following pseudocode attempts to emulate old values using [P0380] (scope_exit here is an RAII object that executes the nullary functor passed to its constructor when it is destroyed):

void fswap(file& x, file& y)
    [[expects: x.closed()]]
    [[excepts: y.closed()]]
    // Postconditions in function definition below to emulate old values.
{
    file old_x = x; // Emulate old values with local copies (not disabled).
    file old_y = y;
    scope_exit ensures([&] { // Check after local objects destroyed.
        if(!std::uncaught_exception()) { // Check only if no throw.
            [[assert: x.closed()]]
            [[assert: y.closed()]]
            [[assert: x == old_y]]
            [[assert: y == old_x]]
        }
    });

    x.open();
    scope_exit close_x([&] { x.close(); });
    y.open();
    scope_exit close_y([&] { y.close(); });
    file t = file::temp();
    t.open;
    scope_exit close_t([&] { t.close(); });

    x.mv(t);
    y.mv(x);
    t.mv(y);
}

This requires boiler-plate code to make sure postconditions are correctly checked only if the function did not throw an exception and in a scope_exit RAII object after all other local objects have been destroyed (because some of these destructors contribute to establishing the postconditions). Still, it never disables old value copies (not even if postconditions are disabled in release builds).
Implementing class invariants is more involved (especially if done automatically, without requiring programmers to manually invoke extra functions to check the invariants). [21] All references reviewed by the authors seem to not consider static and volatile functions not supporting static and volatile invariants respectively.
[21] For example, the following pseudocode attempts to emulation of class invariants using [P0380]:

template<typename T>
class vector {
    bool invariant() const {        // Check invariants at...
        [[assert: empty() == (size() == 0)]]
        [[assert: size() <= capacity()]]
        return true;
    }

public:
    vector()
        [[ensures: invariant()]]    // ...constructor exit (only if no throw).
    { ... }

    ~vector() noexcept
        [[expects: invariant()]]    // ...destructor entry.
    { ... }

    void push_back(T const& value)
        [[expects: invariant()]]    // ...public function entry.
        [[ensures: invariant()]]    // ...public function exit (if no throw).
    try {
        ... // Function body.
    } catch(...) {
        invariant();                // ...public function exit (if throw).
        throw;
    }

    ...
};

This requires boiler-plate code to manually invoke the function that checks the invariants (note that invariants are checked at public function exit regardless of exceptions being thrown while postconditions are not). In case the destructor can throw (e.g., it is declared noexcept(false)), the destructor also requires a try-catch statement similar to the one programmed for push_back to check class invariants at destructor exit when it throws exceptions. Still, an outstanding issue remains to avoid infinite recursion if also empty and size are public functions programmed to check class invariants (because [P0380] does not automatically disable assertions while checking other assertions).
Implementing subcontracting involves a significant amount of complexity and it seems to not be properly supported by any C++ library other than this one (especially when handling multiple inheritance, correctly copying postcondition old values across all overridden contracts deep in the inheritance tree, and correctly reporting the return value to the postconditions of overridden virtual functions in base classes). [22]
[22] For example, it is not really possible to sketch pseudocode based on [P0380] that emulates subcontracting in the general case.

Tutorial
This section is a guide to basic usages of this library.

Non-Member Functions
Contracts for non-member functions are programmed using boost::contract::function. For example (see non_member.cpp):

#include <boost/contract.hpp>

// Contract for a non-member function.
int inc(int& x) {
    int result;
    boost::contract::old_ptr<int> old_x = BOOST_CONTRACT_OLDOF(x);
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(x < std::numeric_limits<int>::max());
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(x == *old_x + 1);
            BOOST_CONTRACT_ASSERT(result == *old_x);
        })
        .except([&] {
            BOOST_CONTRACT_ASSERT(x == *old_x);
        })
    ;

    return result = x++; // Function body.
}

All necessary header files of this library are included by #include <boost/contract.hpp>. Alternatively, programmers can selectively include only the header files they actually need among boost/contract/*.hpp (see Getting Started).
It is possible to specify preconditions, postconditions, and exception guarantees for non-member functions (see Preconditions, Postconditions, and Exception Guarantees).
The boost::contract::function function returns an RAII object that must always be assigned to a local variable of type boost::contract::check (otherwise this library will generate a run-time error, see BOOST_CONTRACT_ON_MISSING_CHECK_DECL). [23] Furthermore, C++11 auto declarations cannot be used here and the 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). [24] The function body is programmed right after the declaration of the RAII object.
[23] The name of this local variable is arbitrary, but c is often used in this documentation for check or caminiti ;-).
[24] Rationale: C++17 zero-copy guarantee on function return values skips the trick this library uses to force a compile-time error when auto is incorrectly used instead of boost::contract::check. The library is still able to generate a run-time error in this case on C++17. In any case, after reading this documentation it should be evident to programmers that auto should not be used in boost::contract::check declarations so this misuse of auto should not be an issue in practice.
In some cases, it might be necessary to program some code before the contract. 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.
At construction, the boost::contract::check RAII object for non-member functions does the following (enclosing function entry):
Check preconditions, by calling the nullary functor r() passed to .precondition(r).
At destruction instead (enclosing function exit):
If the function body did not throw an exception:
Check postconditions, by calling the nullary functor s() passed to .postcondition(s).
Else:
Check exception guarantees, by calling the nullary functor e() passed to .except(e).
This ensures that non-member function contracts are correctly checked at run-time (see Function Calls). (Also note that functions will correctly check their contracts even when they are called via function pointers, function objects, etc.)
A non-member function can avoid calling boost::contract::function for efficiency but only when it has no preconditions, no postconditions, and no exception guarantees.

Preconditions
When preconditions are specified, they are programmed using a functor r passed to .precondition(r) that can be called with no parameters as r(). Contracts that do not have preconditions simply do not call .precondition(...). Preconditions must appear before postconditions and exception guarantees when these are all present (see Postconditions and Exception Guarantees).
C++11 lambda functions are convenient to program preconditions, but any other nullary functor can be used (see No Lambda Functions). [25] For example, for boost::contract::function (similarly for public functions, instead destructors do not have preconditions and constructors use boost::contract::constructor_precondition, see Public Functions, Destructors, and Constructors):
[25] Lambda functions with no parameters can be programmed in C++11 as [...] () { ... } but also equivalently as [...] { ... }. This second from is often used in this documentation omitting the empty parameter list () for brevity.

void f(...) {
    boost::contract::check c = boost::contract::function()  // Same for all other contracts.
        .precondition([&] {                                 // Capture by reference or value...
            BOOST_CONTRACT_ASSERT(...);                     // ...and should not modify captures.
            ...
        })
        ...
    ;

    ...
}

The precondition functor should capture all the variables that it needs to assert the preconditions. These variables can be captured by value when the overhead of copying such variables is acceptable. [26] In any case, precondition assertions should not modify the value of the captured variables, even when those are captured by reference (see Constant-Correctness).
[26] In this documentation preconditions often capture variables by reference to avoid extra copies.
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). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if `bool_cond` contains commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call the failure handler boost::contract::precondition_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if calling the functor specified via .precondition(...) throws any exception. 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.).
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. 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). 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).

Postconditions
When postconditions are specified, they are programmed using a functor s passed to .postcondition(s) that can be called with no parameters as s(). Contracts that do not have postconditions simply do not call .postcondition(...). Postconditions must appear after preconditions but before exception guarantees when these are all present (see Preconditions and Exception Guarantees).
C++11 lambda functions are convenient to program postconditions, but any other nullary functor can be used (see No Lambda Functions). For example, for boost::contract::function (similarly for all other contracts):

void f(...) {
    boost::contract::check c = boost::contract::function()  // Same for all other contracts.
        ...
        .postcondition([&] {                                // Capture by reference...
            BOOST_CONTRACT_ASSERT(...);                     // ...but should not modify captures.
            ...
        })
        ...
    ;

    ...
}

The postcondition functor should capture all variables that it needs to assert the postconditions. 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 constructed). Postconditions can also capture return and old values (see Return Values and Old Values). In any case, postcondition assertions should not modify the value of the captured variables (see Constant-Correctness).
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). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if `bool_cond` has commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call the failure handler boost::contract::postcondition_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if calling the functor specified via .postcondition(...) throws any exception. 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.).
For non-void virtual public functions and 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).

Return Values
In non-void functions, postconditions might need to access the function return value to program assertions. 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). [27] For example, for boost::contract::function (similarly for all other contracts):
[27] The name of the local variable that holds the return value is arbitrary, but result is often used in this documentation.

return_type f(...) {
    return_type result;                                     // Must be later assigned to return value.
    boost::contract::check c = boost::contract::function()  // Same for all other contracts.
        ...
        .postcondition([&] {                                // Also capture `result` reference...
            BOOST_CONTRACT_ASSERT(result ...);              // ...but should not modify captures.
            ...
        })
        ...
    ;

    ...                                                     // Assign `result` at each return.
}

At any point where the enclosing function returns, programmers are responsible to assign the result variable to the expression being returned. This can be done ensuring that all return statements in the function are of the form:

return result = return_expr;                                // Assign `result` at each return.

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 constructed). 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). In any case, programmers should not modify the result variable in the contract assertions (see Constant-Correctness).
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).
Non-void virtual public functions and 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).

Old Values
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 BOOST_CONTRACT_OLDOF. [28] For example, for boost::contract::function (similarly for all other contracts):
[28] The name of a local variable that holds an old value is arbitrary, but old_variable-name is often used in this documentation.

void f(...) {
    boost::contract::old_ptr<old_type> old_var = BOOST_CONTRACT_OLDOF(old_expr);
    ...                                                     // More old value declarations here if needed.
    boost::contract::check c = boost::contract::function()  // Same for all other contracts.
        ...                                                 // Preconditions shall not use old values.
        .postcondition([&] {                                // Capture by reference...
            BOOST_CONTRACT_ASSERT(*old_var ...);            // ...but should not modify captures.
            ...
        })
        .except([&] {                                       // Capture by reference...
            BOOST_CONTRACT_ASSERT(old_var->...);            // ...but should not modify captures.
            ...
        })
    ;

    ...
}

Old values are handled by this library using the smart pointer class template boost::contract::old_ptr (so programmers do not directly manage allocation and deallocation of the pointed memory). [29] The pointed old value type is automatically qualified as const (so old values cannot be mistakenly changed by contract assertions, see Constant-Correctness). 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).
[29] Rationale: 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 BOOST_CONTRACT_NO_POSTCONDITIONS and BOOST_CONTRACT_NO_EXCEPTS). That is to avoid old value copies when old values are not used, so a pointer, or better a boost::optional, could have been used for that. 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.
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. [30] See Old Value Copies at Body for delaying the copy of old values until after class invariants (for constructors, destructors, and public functions) and preconditions are checked (this allows to program old value expressions under the simplifying assumption that class invariant and precondition assertions are satisfied already).
[30] For example, old value pointers might be null in preconditions when postconditions and exception guarantees are disabled defining BOOST_CONTRACT_NO_POSTCONDITIONS and BOOST_CONTRACT_NO_EXCEPTS, but also when checking an overridden virtual public function contract via subcontracting, etc.
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). C++11 auto declarations can be used with BOOST_CONTRACT_OLDOF for brevity auto old_variable-name = BOOST_CONTRACT_OLDOF(expression). See No Macros to program old values without using BOOST_CONTRACT_OLDOF (e.g., on compilers that do not support variadic macros).
This library ensures that old values are copied only once. This library also ensures that old values are never copied when postconditions and exception guarantees are disabled defining both BOOST_CONTRACT_NO_POSTCONDITIONS and BOOST_CONTRACT_NO_EXCEPTS (note that both these two macros must be defined, defining only BOOST_CONTRACT_NO_POSTCONDITIONS or only BOOST_CONTRACT_NO_EXCEPTS is not sufficient to prevent the run-time cost of old value copies).

Exception Guarantees
When exception guarantees are specified, they are programmed using a functor e passed to .except(e) that can be called with no parameters as e(). Contracts that do not have exception guarantees simply do not call .except(...). Exception guarantees must appear after both preconditions and postconditions when these are all present (see Preconditions and Postconditions).
C++11 lambda functions are convenient to program exception guarantees, but any other nullary functor can be used (see No Lambda Functions). For example, for boost::contract::function (similarly for all other contracts):

void f(...) {
    boost::contract::check c = boost::contract::function()  // Same for all other contracts.
        ...
        .except([&] {                                       // Capture by reference...
            BOOST_CONTRACT_ASSERT(...);                     // ...but should not modify captures.
            ...
        })
    ;

    ...
}

The exception guarantee functor should capture all variables that it needs to assert the exception guarantees. 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 constructed). Exception guarantees can also capture old values (see Old Values) but they should not access the function return value instead (because the return value will not be properly set when the function throws an exception). In any case, exception guarantee assertions should not modify the value of the captured variables (see Constant-Correctness).
In real code, it might be difficult to program meaningful exception guarantees without resorting to expensive old value copies that will slow down execution. 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). In any case, these performance considerations are ultimately left to programmers and their specific application domain.
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). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if `bool_cond` has commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call the failure handler boost::contract::except_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if calling the functor specified via .except(...) throws any exception. 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).
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. 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). Therefore, programmers should not change the exception guarantee failure handler to throw exceptions.

Class Invariants
Public member functions, constructors, and destructors can be programmed to check class invariants. When class invariants are specified, they are programmed in a public const function named invariant taking no argument and returning void. Classes that do not have invariants, simply do not declare the invariant function. [31] For example:
[31] This library uses template meta-programming (SFINAE-based introspection techniques) to check invariants only for classes that declare a member function named BOOST_CONTRACT_INVARIANT_FUNC.

class u {
public:                                 // Must be public.
    void invariant() const {            // Must be const.
        BOOST_CONTRACT_ASSERT(...);
        ...
    }

    ...
};

This member function must be const because contracts should not modify the object state (see Constant-Correctness). This library will generate a compile-time error if the const qualifier is missing (unless BOOST_CONTRACT_PERMISSIVE is defined).
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). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if `bool_cond` has commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call failure handlers boost::contract::entry_invariant_failure or boost::contract::exit_invariant_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if the invariant function throws an exception when invariants are checked at function entry or exit respectively. 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.).
See Access Specifiers to avoid making the invariant member function public. [32] See BOOST_CONTRACT_INVARIANT_FUNC to use a name different from invariant (e.g., because invariant clashes with other names in user-defined classes).
[32] In this documentation the invariant member function is often declared public for simplicity. 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 boost::contract::access as explained in Access Specifiers).
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). Therefore, it might be best for both classes and structs (and also unions, 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.
See Volatile Public Functions to program invariants for classes with volatile public functions.

Static Class Invariants
Static public functions can be programmed to check static class invariants. When static class invariants are specified, they are programmed in a public static function named static_invariant taking no argument and returning void. Classes that do not have static class invariants, simply do not declare the static_invariant function. [33] For example:
[33] This library uses template meta-programming (SFINAE-based introspection techniques) to check static invariants only for classes that declare a member function named BOOST_CONTRACT_STATIC_INVARIANT_FUNC.

class u {
public:                                 // Must be public.
    static void static_invariant() {    // Must be static.
        BOOST_CONTRACT_ASSERT(...);
        ...
    }

    ...
};

This member function must be static (and it correctly cannot access the object this). This library will generate a compile-time error if the static classifier is missing (unless the BOOST_CONTRACT_PERMISSIVE macro is defined).
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). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if condition has commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call failure handlers boost::contract::entry_invariant_failure or boost::contract::exit_invariant_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if the static_invariant function throws an exception when invariants are checked at function entry or exit respectively. 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.).
See Access Specifiers to avoid making static_invariant member function public. [34] See 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). [35]
[34] In this documentation the static_invariant member function is often declared public for simplicity. 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 boost::contract::access as explained in Access Specifiers).
[35] Rationale: In C++, it is not possible to overload a member function based on the static classifier. Therefore, this library has to use different names for the member functions checking non-static and static class invariants (namely for BOOST_CONTRACT_INVARIANT_FUNC and for BOOST_CONTRACT_STATIC_INVARIANT_FUNC).

Constructors
Contracts for constructors are programmed using the boost::contract::constructor function and the boost::contract::constructor_precondition base class. For example (see public.cpp):

class unique_identifiers :
    private boost::contract::constructor_precondition<unique_identifiers>
{
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(size() >= 0);
    }

public:
    // Contract for a constructor.
    unique_identifiers(int from, int to) :
        boost::contract::constructor_precondition<unique_identifiers>([&] {
            BOOST_CONTRACT_ASSERT(from <= to);
        })
    {
        boost::contract::check c = boost::contract::constructor(this)
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(size() == (to - from + 1));
            })
        ;

        // Constructor body.
        for(int id = from; id <= to; ++id) vect_.push_back(id);
    }

    /* ... */
};

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 boost::contract::constructor). Constructor preconditions are specified using the boost::contract::constructor_precondition base class instead (but considerations from Preconditions apply also to the precondition functor passed to boost::contract::constructor_precondition). Programmes should not access the object *this from constructor preconditions (because the object does not exists yet before the constructor body is executed). [36] Constructors without preconditions simply do not explicitly initialize the boost::contract::constructor_precondition base (because boost::contract::constructor_precondition default constructor checks no contract). When the boost::contract::constructor_precondition base class is used: [37]
[36] See No Lambda Functions to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
[37] There is a MSVC bug that was fixed in MSVC 2013 for which lambdas cannot be used in constructor member initialization lists for templates. 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).
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).
Its inheritance access specifier should always be private (so this extra base class does not alter the public inheritance tree of its derived classes).
It takes the derived class as template parameter (the Curiously Recursive Template Pattern (CRTP) is used here to avoid ambiguity resolution errors with multiple inheritance). [38]
[38] Rationale: The boost::contract::constructor_precondition takes the derived class as its template parameter so the instantiated template type is unique for each derived class. This always avoids base class ambiguity resolution errors even when multiple inheritance is used. Note that 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).
A class can avoid inheriting from boost::contract::constructor_precondition for efficiency but only when all its constructors have no preconditions.
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). [39] 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). [40] The boost::contract::constructor function takes this as a parameter (because constructors check class invariants, see Class Invariants).
[39] See No Lambda Functions to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
[40] See No Lambda Functions to enforce these constraints at compile-time (but not recommended because of extra boiler-plate code).
The boost::contract::constructor function returns an RAII object that must always be assigned to a local variable of type boost::contract::check (otherwise this library will generate a run-time error, see BOOST_CONTRACT_ON_MISSING_CHECK_DECL). Furthermore, C++11 auto declarations cannot be used here and the 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). The constructor body is programmed right after the declaration of the RAII object.
At construction, the boost::contract::check RAII object for constructors does the following (enclosing constructor entry):
Check static class invariants, by calling type-of(*this)::static_invariant() (but not non-static class invariants because the object does not exist yet).
At destruction instead (enclosing constructor exit):
Check static class invariants, by calling type-of(*this)::static_invariant().
If the constructor body did not throw an exception:
Check non-static class invariants, by calling this->invariant().
Check postconditions, by calling the nullary functor s() passed to .postcondition(s).
Else:
Check exception guarantees, by calling the nullary functor e() passed to .except(e).
This together with C++ object construction mechanism of base classes and the use of boost::contract::constructor_precondition ensures that the constructor contracts are correctly checked at run-time (see Constructor Calls).
A constructor can avoid calling boost::contract::constructor for efficiency but only when it has no postconditions, no exception guarantees, and its class has no invariants (even if 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).
The default constructor and copy constructor automatically generated by C++ will not check contracts. 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 boost::contract::constructor and boost::contract::constructor_precondition. Similar considerations apply to all other constructors automatically generated by C++ (e.g., the move constructor).
Private and protected constructors can omit 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). They could still use boost::contract::constructor_precondition to check preconditions before member initializations, and even use boost::contract::function (but not boost::contract::constructor) to only check postconditions and exception guarantees without checking class invariants and without calling .precondition(...) (see Private and Protected Functions). For example:

class u : private boost::contract::constructor_precondition<u> {
protected:
    // Contract for a protected constructor (same for private constructors).
    u() : // Still use this base class to check constructor preconditions.
        boost::contract::constructor_precondition<u>([&] {
            BOOST_CONTRACT_ASSERT(...);
            ...
        })
    {
        // Following will correctly not check class invariants.
        boost::contract::check c = boost::contract::function()
            // Do not use `.precondition(...)` here.
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(...);
                ...
            })
            .except([&] {
                BOOST_CONTRACT_ASSERT(...);
                ...
            })
        ;

        ... // Constructor body.
    }

    ...
};

Destructors
Contracts for destructors are programmed using boost::contract::destructor. For example (see public.cpp):

class unique_identifiers :
    private boost::contract::constructor_precondition<unique_identifiers>
{
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(size() >= 0);
    }

public:
    // Contract for a destructor.
    virtual ~unique_identifiers() {
        // Following contract checks class invariants.
        boost::contract::check c = boost::contract::destructor(this);

        // Destructor body here... (do nothing in this example).
    }

    /* ... */
};

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). 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). [41] 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++ and in fact they are implicitly declared noexcept since C++11). [42] The boost::contract::destructor function takes this as a parameter (because destructors check class invariants, see Class Invariants).
[41] See No Lambda Functions to enforce this constraint at compile-time (but not recommended because of extra boiler-plate code).
[42] Exceptions guarantees in destructors can access both the object this and its old value because the object exited before executing the destructor body and it still exists given the destructor body failed throwing an exception so the object should still be properly constructed and satisfy its class invariants.
The boost::contract::destructor function returns an RAII object that must always be assigned to a local variable of type boost::contract::check (otherwise this library will generate a run-time error, see BOOST_CONTRACT_ON_MISSING_CHECK_DECL). Furthermore, C++11 auto declarations cannot be used here and the 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). The destructor body is programmed right after the declaration of the RAII object.
At construction, the boost::contract::check RAII object for destructors does the following (enclosing destructor entry):
Check static and non-static class invariants, by calling type-of(*this)::static_invariant() AND this->invariant().
At destruction instead (enclosing destructor exit):
Check static class invariants, by calling type-of(*this)::static_invariant().
If the destructor body did not throw an exception:
Check postconditions, by calling the nullay functor s() passed to .postcondition(s).
Else (even if destructors should generally be programmed not to throw in C++):
Check non-static class invariants, by calling this->invariant() (because the object was not successfully destructed).
Check exception guarantees, by calling the nullary functor e() passed to .except(e).
This together with C++ object destruction mechanism of base classes ensures that destructor contracts are correctly checked at run-time (see Destructor Calls).
A destructor can avoid calling boost::contract::destructor for efficiency but only when it has no postconditions, no exception guarantees, and its class has no invariants (even if 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).
The default destructor automatically generated by C++ will not check contracts. 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 boost::contract::destructor.
Private and protected destructors can omit 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). They could use boost::contract::function (but not boost::contract::destructor) to only check postconditions and exception guarantees without checking class invariants and without calling .precondition(...) (see Private and Protected Functions). For example:

class u {
protected:
    // Contract for a protected destructor (same for private destructors).
    virtual ~u() {
        // Following will correctly not check class invariants.
        boost::contract::check c = boost::contract::function()
            // Do not use `.precondition(...)` here.
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(...);
                ...
            })
            // Could use `.except(...)` here in rare cases of destructors declared to throw.
        ;

        ... // Destructor body.
    }

    ...
};

Public Functions
Contracts for public functions are programmed using boost::contract::public_function. In this section, let's consider public functions that are not static, not virtual, and do not override any function from base classes. For example (see public.cpp):

class unique_identifiers :
    private boost::contract::constructor_precondition<unique_identifiers>
{
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(size() >= 0);
    }

public:
    // Contract for a public function (but no static, virtual, or override).
    bool find(int id) const {
        bool result;
        boost::contract::check c = boost::contract::public_function(this)
            .postcondition([&] {
                if(size() == 0) BOOST_CONTRACT_ASSERT(!result);
            })
        ;

        // Function body.
        return result = std::find(vect_.begin(), vect_.end(), id) !=
                vect_.end();
    }

    /* ... */
};

It is possible to specify preconditions, postconditions, and exception guarantees for public functions (see Preconditions, Postconditions, and Exception Guarantees). When called from non-static public functions, the boost::contract::public_function function takes this as a parameter (because public functions check class invariants, see Class Invariants).
The boost::contract::public_function function returns an RAII object that must always be assigned to a local variable of type boost::contract::check (otherwise this library will generate a run-time error, see BOOST_CONTRACT_ON_MISSING_CHECK_DECL). Furthermore, C++11 auto declarations cannot be used here and the 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). The public function body is programmed right after the declaration of the RAII object.
At construction, the boost::contract::check RAII object for public functions does the following (enclosing public function entry):
Check static and non-static class invariants, by calling type-of(*this)::static_invariant() AND this->invariant().
Check preconditions, by calling the nullary functor r() passed to .precondition(r).
At destruction instead (enclosing public function exit):
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).
If the function body did not throw an exception:
Check postconditions, by calling the nullary functor s() passed to .postcondition(s).
Else:
Check exception guarantees, by calling the nullary functor e() passed to .except(e).
This ensures that public function contracts are correctly checked at run-time (see Public Function Calls).
A public function can avoid calling 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.
The default copy assignment operator automatically generated by C++ will not check contracts. 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 boost::contract::public_function. Similar considerations apply to all other operators automatically generated by C++ (e.g., the move operator).

Virtual Public Functions
Contracts for public functions are programmed using boost::contract::public_function. In this section, let's consider public functions that are virtual but that do not override any function from base classes. For example (see public.cpp):

class unique_identifiers :
    private boost::contract::constructor_precondition<unique_identifiers>
{
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(size() >= 0);
    }

public:
    // Contract for a public virtual function (but no override).
    virtual int push_back(int id, boost::contract::virtual_* v = 0) { // Extra `v`.
        int result;
        boost::contract::old_ptr<bool> old_find =
                BOOST_CONTRACT_OLDOF(v, find(id)); // Pass `v`.
        boost::contract::old_ptr<int> old_size =
                BOOST_CONTRACT_OLDOF(v, size()); // Pass `v`.
        boost::contract::check c = boost::contract::public_function(
                v, result, this) // Pass `v` and `result`.
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(!find(id)); // ID cannot be already present.
            })
            .postcondition([&] (int const result) {
                if(!*old_find) {
                    BOOST_CONTRACT_ASSERT(find(id));
                    BOOST_CONTRACT_ASSERT(size() == *old_size + 1);
                }
                BOOST_CONTRACT_ASSERT(result == id);
            })
        ;

        // Function body.
        vect_.push_back(id);
        return result = id;
    }

    /* ... */
};

Virtual public functions must declare an extra trailing parameter of type boost::contract::virtual_* with default value 0 (i.e., nullptr). [43] 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.). Programmers must pass the extra virtual parameter as the very first argument to all BOOST_CONTRACT_OLDOF and boost::contract::public_function calls in the virtual public function definition. [44]
[43] The name of this extra parameter is arbitrary, but v is often used in this documentation.
[44] Rationale: The 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). Furthermore, this parameter is internally used by this library to pass result and old values that are evaluated by the overriding function to overridden virtual functions in base classes, and also to check preconditions, postconditions, and exception guarantees of overridden virtual functions to implement subcontracting.
When called from virtual public functions, the boost::contract::public_function function takes this as a parameter (because public functions check class invariants, see Class Invariants). For virtual public functions returning void:

class u {
public:
    // A void virtual public function (that does not override).
    virtual void f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) {
        boost::contract::check c = boost::contract::public_function(
                v, this)                                    // No result parameter...
            .precondition([&] { ... })
            .postcondition([&] { ... })                     // ...so nullary functor.
            .except([&] { ... })
        ;

        ...
    }

    ...
}

For virtual public functions not returning void, programmers must also pass a reference to the function return value as the second argument to boost::contract::public_function. 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): [45]
[45] Rationale: 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 when subcontracting.

class u {
public:
    // A void virtual public function (that does not override).
    virtual t f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) {
        t result;
        boost::contract::check c = boost::contract::public_function(
                v, result, this)                            // Result parameter...
            .precondition([&] { ... })
            .postcondition([&] (t const& result) { ... })   // ...so unary functor.
            .except([&] { ... })
        ;

        ...                                                 // Assign `result` at each return.
    }

    ...
}

It is the responsibility of the programmers to pass the extra virtual parameter v to all BOOST_CONTRACT_OLDOF and boost::contract::public_function calls within virtual public functions, and also to pass the return value reference after v to boost::contract::public_function for non-void virtual public functions. 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). [46]
[46] Rationale: This library does not require programmers to specify the function type when using boost::contract::public_function for non-overriding virtual public functions. 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. 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.
Mnemonics:
When v is present, always pass it as the first argument to boost::contract::public_function and BOOST_CONTRACT_OLDOF.
Always pass result to boost::contract::public_function right after v for non-void functions.
For the rest, considerations made in Public Functions apply to virtual public functions as well.
A virtual public function should always call 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.

Public Function Overrides (Subcontracting)
Contracts for public functions are programmed using boost::contract::public_function. In this section, let's consider public functions (virtual or not) that override virtual public functions from one or more public base classes. For example (see public.cpp): [47]
[47] In this documentation, function overrides are often marked with the code comment /* override */. 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).

class identifiers
    #define BASES public unique_identifiers
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types; // Bases typedef.
    #undef BASES

    void invariant() const { // Check in AND with bases.
        BOOST_CONTRACT_ASSERT(empty() == (size() == 0));
    }

public:
    // Contract for a public function override.
    int push_back(int id, boost::contract::virtual_* v = 0) /* override */ {
        int result;
        boost::contract::old_ptr<bool> old_find =
                BOOST_CONTRACT_OLDOF(v, find(id));
        boost::contract::old_ptr<int> old_size =
                BOOST_CONTRACT_OLDOF(v, size());
        boost::contract::check c = boost::contract::public_function<
            override_push_back // Pass override plus below function pointer...
        >(v, result, &identifiers::push_back, this, id) // ...and arguments.
            .precondition([&] { // Check in OR with bases.
                BOOST_CONTRACT_ASSERT(find(id)); // ID can be already present.
            })
            .postcondition([&] (int const result) { // Check in AND with bases.
                if(*old_find) BOOST_CONTRACT_ASSERT(size() == *old_size);
            })
        ;

        // Function body.
        if(!find(id)) unique_identifiers::push_back(id); // Else, do nothing.
        return result = id;
    }
    BOOST_CONTRACT_OVERRIDE(push_back) // Define `override_push_back`.

    /* ... */
};

The extra typedef declared using BOOST_CONTRACT_BASE_TYPES is required by this library for derived classes and it is internally used detect base classes for subcontracting (see Base Classes).
When called from public function overrides, the boost::contract::public_function function template takes an explicit template argument override_function-name that must be defined using BOOST_CONTRACT_OVERRIDE:

BOOST_CONTRACT_OVERRIDE(func_name)

This can be declared at any point in the public section of the enclosing class (see Access Specifiers to use BOOST_CONTRACT_OVERRIDE in a non-public section of the class instead). 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). 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). For convenience BOOST_CONTRACT_OVERRIDES can be used with multiple function names instead of repeating BOOST_CONTRACT_OVERRIDE for each function name (on compilers that support variadic macros). For example, for three functions named f, g, and h (but same for any other number of functions), the following:

BOOST_CONTRACT_OVERRIDES(f, g, h)

Is equivalent to: [48]
[48] This library does not provider an equivalent of BOOST_CONTRACT_NAMED_OVERRIDE that operates on multiple function names at once (simply because programmers will probably not use BOOST_CONTRACT_NAMED_OVERRIDE often in the first place).

BOOST_CONTRACT_OVERRIDE(f)
BOOST_CONTRACT_OVERRIDE(g)
BOOST_CONTRACT_OVERRIDE(h)

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. [49]
[49] 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 boost::contract::virtual_* parameter and searched recursively only in public base classes passed to BOOST_CONTRACT_BASE_TYPES because only those are considered for subcontracting.
Public function overrides must always list the extra trailing parameter of type boost::contract::virtual_* with default value 0 (i.e., nullptr), even when they are not declared virtual (because this parameter is present in the signature of the virtual function being overridden from base classes). Programmers must pass the extra virtual parameter as the very first argument to all BOOST_CONTRACT_OLDOF and boost::contract::public_function calls in the public function override definition (see Virtual Public Functions).
When called from public function overrides, the 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. [50] For public function overrides returning void:
[50] Rationale: The object this is passed after the function pointer to follow std::bind's syntax. The function pointer and references to all function arguments are needed for public function overrides because this library has to 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).

class u {
public:
    // A void public function override.
    void f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::check c = boost::contract::public_function<override_f>(
                v, &u::f, this, a_1, ..., a_n)              // No result parameter...
            .precondition([&] { ... })
            .postcondition([&] { ... })                     // ...so nullary functor.
            .except([&] { ... })
        ;

        ...
    }

    BOOST_CONTRACT_OVERRIDE(f)

    ...
}

For public function overrides not returning void, programmers must also pass a reference to the function return value as the second argument to boost::contract::public_function (this library will generate a compile-time error otherwise). [51] 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):
[51] Rationale: 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. 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).

class u {
public:
    // A non-void public function override.
    t f(t_1 a_1, ..., t_n a_n, boost::contract::virtual_* v = 0) /* override */ {
        t result;
        boost::contract::check c = boost::contract::public_function<override_f>(
                v, result, &u::f, this, a_1, ..., a_n)      // Result parameter...
            .precondition([&] { ... })
            .postcondition([&] (t const& result) { ... })   // ...so unary functor.
            .except([&] { ... })
        ;

        ...                                                 // Assign `result` at each return.
    }

    BOOST_CONTRACT_OVERRIDE(f)

    ...
}

This library will throw 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. [52]
[52] Rationale: The boost::bad_any_cast exception could not used here because it does not print the from- and to- type names (so it is not descriptive enough).
It is the responsibility of the programmers to pass the extra virtual parameter v to all BOOST_CONTRACT_OLDOF and boost::contract::public_function calls within public function overrides, and also to pass the return value reference after v to boost::contract::public_function for non-void public function overrides. 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).
Mnemonics:
When override_... is present, always pass it as template parameter to boost::contract::public_functioon.
When v is present, always pass it as the first argument to boost::contract::public_function and BOOST_CONTRACT_OLDOF.
Always pass result to boost::contract::public_function right after v for non-void functions.
At construction, the boost::contract::check RAII object for public function overrides does the following (enclosing public function override entry):
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().
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.
At destruction instead (enclosing public function override exit):
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).
If the function body did not throw an exception:
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).
Else:
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.
This ensures that public function override contracts and subcontracts are correctly checked at run-time (see Public Function Calls).
For the rest, considerations made in Virtual Public Functions apply to public function overrides as well.
A public function override should always call 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.

Base Classes (Subcontracting)
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 BOOST_CONTRACT_BASE_TYPES. For example (see base_types.cpp):

class chars
    #define BASES /* local macro (for convenience) */ \
        private boost::contract::constructor_precondition<chars>, \
        public unique_chars, \
        public virtual pushable<char>, \
        virtual protected has_size, \
        private has_empty
    : BASES // Bases of this class.
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types; // Bases typedef.
    #undef BASES // Undefine local macro.

    /* ... */

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)). Being a local macro, BASES must be undefined using #undef BASES after it has been used to declare base_types (to avoid name clashes and macro redefinition errors). [53]
[53] The name of this local macro is arbitrary, but BASES is often used in this documentation.
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). As already noted in Constructors, when the extra base 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.
Each base passed to 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++). 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. [54] It is the responsibility of the programmers to make sure that all bases passed to 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).
[54] Rationale: 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). BOOST_CONTRACT_BASE_TYPES inspects each inheritance access level using preprocessor meta-programming and removes non-public bases from the list of bases inspected for subcontracting. 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). Therefore, this library relies on inheritance access levels to program the preprocessor to correctly identify the next base class token in the inheritance list (thus inheritance access levels must always be explicit specified by programmers).
Mnemonics:
Always explicitly specify the inheritance access level public, protected, or private for base classes passed to BOOST_CONTRACT_BASE_TYPES.
See Access Specifiers to avoid making the base_types member type public. [55] See 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).
[55] In this documentation the base_type member type is often declared public for simplicity. 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 boost::contract::access as explained in Access Specifiers).

Static Public Functions
Contracts for public functions are programmed using boost::contract::public_function. In this section, let's consider static public functions. For example (see static_public.cpp):

template<class C>
class make {
public:
    static void static_invariant() { // Static class invariants.
        BOOST_CONTRACT_ASSERT(instances() >= 0);
    }

    // Contract for a static public function.
    static int instances() {
        // Explicit template parameter `make` (check static invariants).
        boost::contract::check c = boost::contract::public_function<make>();

        return instances_; // Function body.
    }

    /* ... */

It is possible to specify preconditions, postconditions, and exception guarantees for static public functions (see Preconditions, Postconditions, and Exception Guarantees). When called from static public functions, 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 is specified as an explicit template parameter (the class type is required to check static class invariants, see Class Invariants):

class u {
public:
    // A static public function.
    static void f() {
        boost::contract::check c = boost::contract::public_function<u>() // Class type `u` as explicit template parameter.
            .precondition([&] { ... })
            .postcondition([&] { ... })
            .except([&] { ... })
        ;

        ...
    }

    ...
};

The boost::contract::public_function function returns an RAII object that must be assigned to a local variable of type boost::contract::check (otherwise this library will generate a run-time error, see BOOST_CONTRACT_ON_MISSING_CHECK_DECL). Furthermore, C++11 auto declarations cannot be used here and the 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). The static public functions body is programmed right after the declaration of the RAII object.
At construction, the boost::contract::check RAII object for static public functions does the following (enclosing static public function entry):
Check static class invariants, by calling class-type::static_invariant() (but never non-static class invariants).
Check preconditions, by calling the nullary functor r() passed to .precondition(r).
At destruction instead (enclosing static public function exit):
Check static class invariants, by calling class-type::static_invariant() (even if the function body threw an exception, but never non-static class invariants).
If the function body did not throw an exception:
Check postconditions, by calling the nullary functor s() passed to .postcondition(s).
Else:
Check exception guarantees, by calling the nullary functor e() passed to .except(e).
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).
A static public function can avoid calling 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).

Advanced
This section is a guide to advanced usages of this library.

Pure Virtual Public Functions
In C++, pure virtual functions are allowed to have a default implementation as long as such implementation is programmed out-of-line so defined outside the class declaring the pure virtual function virtual ... = 0;.
Contracts for pure virtual public functions are programmed using the boost::contract::public_function function like for (non-pure) virtual public functions (all consideration made in Virtual Public Functions apply). However, contracts have to be programmed out-of-line, in the default implementation of the pure virtual function. For example (see pure_virtual_public.cpp):

template<typename Iterator>
class range {
public:
    // Pure virtual function declaration (contract in definition below).
    virtual Iterator begin(boost::contract::virtual_* v = 0) = 0;

    /* ... */
};

// Pure virtual function default implementation (out-of-line in C++).
template<typename Iterator>
Iterator range<Iterator>::begin(boost::contract::virtual_* v) {
    Iterator result; // As usual, virtual pass `result` right after `v`...
    boost::contract::check c = boost::contract::public_function(v, result, this)
        .postcondition([&] (Iterator const& result) {
            if(empty()) BOOST_CONTRACT_ASSERT(result == end());
        })
    ;

    // Pure function body (never executed by this library).
    assert(false);
    return result;
}

This library will never actually execute the pure virtual function body while it is calling the pure virtual function default implementation to check contracts for subcontracting. Therefore, programmers can safely assert(false) at the beginning of the body if they intend for that body to never be executed (or they can program a working body in case they need to use pure virtual function default implementations as usual in C++).

Subcontracting Preconditions Always True or False
As seen in Public Function Overrides, preconditions of overriding public functions are checked in OR with preconditions of overridden virtual public functions. Therefore, if a virtual public function in a base class specifies no precondition then preconditions specified by all its overriding functions in derived classes will have no effect (because when checked in OR with the overridden function from the base class that has no preconditions, they will always pass): [56]
[56] This consequence of the substitution principle that if any function in an inheritance hierarchy has no preconditions, then preconditions on functions overriding it have no useful effect is also explicitly mentioned in the contract documentation of the D Programming Language (see [Bright04]).

class u { // Some base class.
public:
    virtual void f(boost::contract::virtual_* v = 0) {
        boost::contract::check c = boost::contract::public_function(v, this)
            // No preconditions, same as `ASSERT(true)`.
            ...
        ;

        ...
    }

    ...
};

This correctly reflects the fact that the overridden function in the base class can be called from any context (because it has no precondition) and so must all its overriding functions in all derived classes in accordance to the substitution principle. In other words, the code above has the effect as declaring the virtual public function in the base class with a single precondition BOOST_CONTRACT_ASSERT(true) that will always trivially pass:

class u { // Some base class.
public:
    virtual void f(boost::contract::virtual_* v = 0) {
        boost::contract::check c = boost::contract::public_function(v, this)
            .precondition([] {
                BOOST_CONTRACT_ASSERT(true); // Same as no preconditions.
            })
            ...
        ;

        ...
    }

    ...
};

On the flip side, programmers might sometimes consider to declare a pure virtual public function in a base class with a single precondition BOOST_CONTRACT_ASSERT(false) that will always fail. This indicates that the pure virtual public function can never be called unless it is redefined by a derived class (which is already the case with C++ pure virtual functions) and also that the base class designers have intentionally left it up to derived classes to specify preconditions for the pure virtual function in question. This technique might make sense only for preconditions of pure virtual public functions (otherwise BOOST_CONTRACT_ASSERT(false) will prevent calling virtual public functions in concrete bases). For example (see named_override.cpp):

template<typename T>
class generic_unary_pack {
public:
    virtual void _1(T const& value, boost::contract::virtual_* v = 0) = 0;
    virtual T _1(boost::contract::virtual_* v = 0) const = 0;
};

template<typename T>
void generic_unary_pack<T>::_1(T const& value, boost::contract::virtual_* v) {
    boost::contract::check c = boost::contract::public_function(v, this)
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(false); // Defer preconditions to overrides.
        })
    ;
    assert(false);
}

/* ... */

That said, the need to declare such a precondition BOOST_CONTRACT_ASSERT(false) that will always fail might be an indication that the base class interface is not correctly designed. In general, the base class interface should still contain all functions (eventually as pure virtual) that are necessary to program its contracts.

Optional Return Values
It is possible to use boost::optional to handle return values when programmers cannot construct the result variable at its point of declaration before the contract (e.g., because an appropriate constructor for the return type is not available at that point, or just because it would be too expensive to execute an extra initialization of the return value at run-time). [57] For example (see optional_result.cpp):
[57] Rationale: This library uses boost::optional instead of std::optional because std::optional is not available before C++17.

template<unsigned Index, typename T>
T& get(std::vector<T>& vect) {
    boost::optional<T&> result; // Result not initialized here...
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(Index < vect.size());
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(*result == vect[Index]);
        })
    ;

    // Function body (executed after preconditions checked).
    return *(result = vect[Index]); // ...result initialized here instead.
}

In this example the return type is a reference so it does not have default constructor that can be used to initialize result when it is declared before the contract declaration. In addition, Index needs to be validated to be smaller than size() by the precondition before it can be used to retrieve the reference to assign to result so vect[Index] cannot be used to initialize result when it is declared before the contract declaration. Therefore, boost::optional is used to defer result proper initialization until the execution of the function body, after the contract declaration, where Index has been validated by the precondition and vect[Index] can be safely evaluated to initialize result.
As seen in Return Values, it is the responsibility of the programmers to ensure that result is always set to the return value (when the function exits without trowing an exception). This also ensures that result is always set before the postconditions are checked so programmers can always dereference result in postconditions to access the return value (using operator* and operator-> as usual with boost::optional, and without having to explicitly check if result is an empty boost::optional object or not). This can be done ensuring that all return statements in the function are of the form:

boost::optional<return_type> result;
...
return *(result = return_expr); // Assign `result` at each return.

Optional Results in Virtual Public Functions
Similarly, boost::optional can be used to handle the return value passed to contracts of virtual public functions (pure or not) and of public function overrides. As seen in Pure Virtual Public Functions, Virtual Public Functions, and Public Function Overrides, in these cases the return value result must be passed as a parameter to boost::contract::public_function right after the parameter v of type boost::contract::virtual_*. Then the functor passed to .postcondition(...) takes one single parameter of type boost::optional<return-type const&> const&. For example (see optional_result_virtual.cpp):

template<typename T>
T& accessible<T>::at(unsigned index, boost::contract::virtual_* v) {
    boost::optional<T&> result;
    // Pass `result` right after `v`...
    boost::contract::check c = boost::contract::public_function(v, result, this)
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(index < size());
        })
        // ...plus postconditions take `result` as a parameter (not capture).
        .postcondition([&] (boost::optional<T const&> const& result) {
            BOOST_CONTRACT_ASSERT(*result == operator[](index));
        })
    ;

    assert(false);
    return *result;
}

The inner const& in the postcondition functor parameter type boost::optional<... const&> ... is mandatory (while the outer const& in the postcondition functor parameter type boost::optional<...> const& is not). [58]
[58] Rationale: This library requires the postcondition functor parameter to be of type boost::optional<... const&> so the return value does not have to be copied (because of &) while postconditions are still not allowed to change its value (because of const, see Constant-Correctness). In addition, programmers are encouraged to declare the postcondition functor to take its argument also as a constant reference boost::optional<... const&> const& to avoid possibly expensive copies of the boost::optional type itself.

Private and Protected Functions
Private and protected functions do not check class invariants (because they are not part of the public class interface) and they do not subcontract (because they are not accessible at the calling site where the substitution principle applies, see Function Calls). However, programmers may still want to specify preconditions and postconditions for private and protected functions when they want to check correctness of their implementation and usage from within the class, base classes, and friend classes or functions. When programmers decide to specify contracts for private and protected functions, they shall use boost::contract::function (because, like for non-member functions, this does not check class invariants and does not subcontract). For example (see private_protected.cpp):

class counter {
protected: // Protected functions use `function()` (like non-members).
    void set(int n) {
        boost::contract::check c = boost::contract::function()
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(n <= 0);
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == n);
            })
        ;

        n_ = n;
    }

private: // Private functions use `function()` (like non-members).
    void dec() {
        boost::contract::old_ptr<int> old_get = BOOST_CONTRACT_OLDOF(get());
        boost::contract::check c = boost::contract::function()
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(
                        get() + 1 >= std::numeric_limits<int>::min());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == *old_get - 1);
            })
        ;

        set(get() - 1);
    }

    int n_;

    /* ... */

Considerations made in Non-Member Functions apply to private and protected functions as well. See Constructors and Destructors on how to program contracts for private and protected constructors and destructors instead.

Virtual Private and Protected Functions
When private and protected functions are virtual they should still declare the extra virtual parameter of type boost::contract::virtual_* with default value 0 (see Virtual Public Functions) even if that parameter does not have to be passed to BOOST_CONTRACT_OLDOF and boost::contract::function takes no such an argument (so the extra virtual parameter will remain unused and it does not need a name). [59] That is necessary otherwise the private and protected virtual functions cannot be overridden by public functions in derived classes that specify contracts (because the boost::contract::virtual_* = 0 parameter has to be part of signatures for public function overrides). For example (see private_protected_virtual.cpp):
[59] Technically, the extra virtual parameter can still be passed to BOOST_CONTRACT_OLDOF but that is not necessary and it has no effect so it is not done in this documentation.

class counter {
    // Virtual private and protected functions still declare extra
    // `virtual_* = 0` parameter (otherwise they cannot be overridden), but...
protected:
    virtual void set(int n, boost::contract::virtual_* = 0) {
        boost::contract::check c = boost::contract::function() // ...no `v`.
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(n <= 0);
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == n);
            })
        ;

        n_ = n;
    }

private:
    virtual void dec(boost::contract::virtual_* = 0) {
        boost::contract::old_ptr<int> old_get = BOOST_CONTRACT_OLDOF(get()); // ...no `v`.
        boost::contract::check c = boost::contract::function() // ...no `v`.
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(
                        get() + 1 >= std::numeric_limits<int>::min());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == *old_get - 1);
            })
        ;

        set(get() - 1);
    }

    int n_;

    /* ... */

However, public functions in derived classes overriding private or protected virtual functions from base classes shall not specify the extra override_... template parameter to boost::contract::public_function because the overridden functions are private or protected and, not being public, they do not participate to subcontracting (this library will generate a compile-time error if override_... is specified because there will be no virtual public function to override from the base class). For example (see private_protected_virtual.cpp):

class counter10
    #define BASES public counter
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
    #undef BASES

    // Overriding from non-public members so no subcontracting, no override_...

    virtual void set(int n, boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::check c = boost::contract::public_function(v, this)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(n % 10 == 0);
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == n);
            })
        ;

        counter::set(n);
    }

    virtual void dec(boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::old_ptr<int> old_get = BOOST_CONTRACT_OLDOF(v, get());
        boost::contract::check c = boost::contract::public_function(v, this)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(
                        get() + 10 >= std::numeric_limits<int>::min());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == *old_get - 10);
            })
        ;

        set(get() - 10);
    }

    /* ... */

Furthermore, using multiple inheritance it is possible to override functions that are private or protected from one base but public from another base. In this case, public function overrides in derived classes will specify the extra override_... template parameter to boost::contract::public_function (because the overridden functions are private or protected in one base and those do not participate to subcontracting, but public in another base and these participate to subcontracting instead). For example (see private_protected_virtual_multi.cpp):

class countable {
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(get() <= 0);
    }

    virtual void dec(boost::contract::virtual_* v = 0) = 0;
    virtual void set(int n, boost::contract::virtual_* v = 0) = 0;
    virtual int get(boost::contract::virtual_* v = 0) const = 0;
};

/* ... */

class counter10
    #define BASES public countable, public counter // Multiple inheritance.
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
    #undef BASES

    // Overriding from public members from `countable` so use `override_...`.

    virtual void set(int n, boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::check c = boost::contract::public_function<
                override_set>(v, &counter10::set, this, n)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(n % 10 == 0);
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == n);
            })
        ;

        counter::set(n);
    }

    virtual void dec(boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::old_ptr<int> old_get = BOOST_CONTRACT_OLDOF(v, get());
        boost::contract::check c = boost::contract::public_function<
                override_dec>(v, &counter10::dec, this)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(
                        get() + 10 >= std::numeric_limits<int>::min());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(get() == *old_get - 10);
            })
        ;

        set(get() - 10);
    }

    BOOST_CONTRACT_OVERRIDES(set, dec)

    /* ... */

Unfortunately, the code above does not compile on MSVC (at least up to Visual Studio 2015) because MSVC incorrectly gives a compile-time error when SFINAE fails due to private or protected access levels. Instead, GCC and Clang correctly implement SFINAE failures due to private and protected functions so the code above correctly complies on GCC and Clang. Therefore, currently it is not possible to override a function that is public in one base but private or protected in other base using this library on MSVC, but that can correctly be done on GCC or Clang instead.

Friend Functions
Friend functions are not member functions so boost::contract::function can used to program contracts for them and all considerations made in Non-Member Functions apply. For example (see friend.cpp):

class buffer;

class byte {
    friend bool operator==(buffer const& left, byte const& right);

private:
    char value_;

    /* ... */

class buffer {
    // Friend functions are not member functions...
    friend bool operator==(buffer const& left, byte const& right) {
        // ...so check contracts via `function` (which won't check invariants).
        boost::contract::check c = boost::contract::function()
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(!left.empty());
                BOOST_CONTRACT_ASSERT(!right.empty());
            })
        ;

        for(char const* x = left.values_.c_str(); *x != '\0'; ++x) {
            if(*x != right.value_) return false;
        }
        return true;
    }

private:
    std::string values_;

    /* ... */

However, in some cases a friend function might take an object as parameter and it can be logically considered an extension of that object's public interface (essentially at the same level as the object's public functions). In these cases, programmers might chose to program the friend function contracts using boost::contract::public_function (instead of boost::contract::function) so to also check the class invariants of the object passed as parameter (and not just pre- and postconditions). For example (see friend_invariant.cpp): [60]
[60] Rationale: Contract programming proposals for C++ like [N1962] do not provide a mechanism for friend functions to check class invariants of objects passed as parameters. In other words, these proposals do not enable contracts to recognize that in C++ some friend functions logically act as if they were part of the public interface of the objects they take as parameters. This is reasonable for proposals that add contracts to the core language because friend functions are not always meant to extend an object public interface and C++ does not provide a mechanism to programmatically specify when they do and when they do not. However, this library adds the flexibility to let programmers manually specify when friend functions should also check class invariants of the objects they take as parameters (using boost::contract::public_function) and when they should not (using boost::contract::function instead).

template<typename T>
class positive {
public:
    void invariant() const {
        BOOST_CONTRACT_ASSERT(value() > 0);
    }

    // Can be considered an extension of enclosing class' public interface...
    friend void swap(positive& object, T& value) {
        boost::contract::old_ptr<T> old_object_value =
                BOOST_CONTRACT_OLDOF(object.value());
        boost::contract::old_ptr<T> old_value = BOOST_CONTRACT_OLDOF(value);
        // ...so it can be made to check invariants via `public_function`.
        boost::contract::check c = boost::contract::public_function(&object)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(value > 0);
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(object.value() == *old_value);
                BOOST_CONTRACT_ASSERT(value == *old_object_value);
            })
        ;

        T saved = object.value_;
        object.value_ = value;
        value = saved;
    }

private:
    T value_;

    /* ... */

This technique can also be extended to friend functions that take multiple objects as parameters and can be logically considered extensions to the public interfaces of each of these objects. For example:

// Can be considered an extension of multiple objects' public interfaces.
friend void f(class1& object1, class2* object2, type3& value3) {
    // Check preconditions.
    boost::contract::check pre = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(object2 != nullptr);
            ...
        })
    ;
    // Check class invariants for each object (programmers chose the order).
    boost::contract::check inv1 = boost::contract::public_function(&object1);
    boost::contract::check inv2 = boost::contract::public_function(object2);
    // Check postconditions and exception guarantees.
    boost::contract::check post_except = boost::contract::function()
        .postcondition(...)
        .except(...)
    ;

    ... // Function body.
}

Changing the order of the boost::contract::check declarations above, programmers can chose the order for checking class invariants among the different objects passed to the friend function and also whether to check these invariants before or after preconditions, postconditions, and exception guarantees of the friend function (see Non-Member Functions and Public Functions for information on how the RAII objects returned by boost::contract::function and boost::contract::public_function check contract conditions). The example above is programmed to check class1 invariants before class2 invariants (but the order could have been inverted if programmers so chose).
In the example above, preconditions are intentionally programmed to be checked before class invariants so the objects passed to the friend function can be validated by the preconditions before they are passed as pointers to boost::contract::public_function (e.g., check object2 is not null). (Within member functions instead, the object pointer this is always well-formed, its validation is never needed, and boost::contract::public_function checks class invariants before checking preconditions so programming preconditions can be simplified assuming the class invariants are satisfied already, see Public Function Calls.)

Function Overloads
No special attention is required when using this library with overloaded functions or constructors. The only exception is for the function pointer passed to boost::contract::public_function from public function overrides (see Public Function Overrides). When the name of public function override are also overloaded, the related function pointer cannot be automatically deduced by the compiler so programmers have to use static_cast to resolve ambiguities (as usual with pointers to overloaded functions in C++). [61] For example, note how static_cast is used in the following calls to boost::contract::public_function (see overload.cpp):
[61] Rationale: In order to avoid copies, this library takes all function arguments and the return value passed to boost::contract::public_function as references when used within public function overrides. Therefore, the library cannot differentiate when the actual function argument and return types are passed by reference and when they are not. As a result, the library cannot automatically reconstruct the type of the enclosing public function so this type must be deduced from the function pointer passed by programmers to boost::contract::public_function. When this automatic deduction is not possible due to overloaded function names, programmers must explicitly use static_cast to resolve ambiguities as usual in C++ with pointers to overloaded functions.

class string_lines
    #define BASES public lines
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
    #undef BASES

    BOOST_CONTRACT_OVERRIDES(str) // Invoked only once for all `str` overloads.

    std::string str(boost::contract::virtual_* v = 0) const /* override */ {
        std::string result;
        boost::contract::check c = boost::contract::public_function<
                override_str>(
            v, result,
            // `static_cast` resolves overloaded function pointer ambiguities.
            static_cast<std::string (string_lines::*)(
                    boost::contract::virtual_*) const>(&string_lines::str),
            this
        );

        return result = str_;
    }

    // Overload on (absence of) `const` qualifier.
    std::string& str(boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::check c = boost::contract::public_function<
                override_str>(
            v, str_,
            // `static_cast` resolves overloaded function pointer ambiguities.
            static_cast<std::string& (string_lines::*)(
                    boost::contract::virtual_*)>(&string_lines::str),
            this
        );

        return str_;
    }

    BOOST_CONTRACT_OVERRIDES(put) // Invoked only once for all `put` overloads.

    void put(std::string const& x,
            boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::old_ptr<std::string> old_str =
                BOOST_CONTRACT_OLDOF(v, str());
        boost::contract::check c = boost::contract::public_function<
                override_put>(
            v,
            // `static_cast` resolves overloaded function pointer ambiguities.
            static_cast<void (string_lines::*)(std::string const&,
                    boost::contract::virtual_*)>(&string_lines::put),
            this, x
        )
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(str() == *old_str + x + '\n');
            })
        ;

        str_ = str_ + x + '\n';
    }

    // Overload on argument type.
    void put(char x, boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::old_ptr<std::string> old_str =
                BOOST_CONTRACT_OLDOF(v, str());
        boost::contract::check c = boost::contract::public_function<
                override_put>(
            v,
            // `static_cast` resolves overloaded function pointer ambiguities.
            static_cast<void (string_lines::*)(char,
                    boost::contract::virtual_*)>(&string_lines::put),
            this, x
        )
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(str() == *old_str + x + '\n');
            })
        ;

        str_ = str_ + x + '\n';
    }

    // Overload on argument type and arity (also with default parameter).
    void put(int x, bool tab = false,
            boost::contract::virtual_* v = 0) /* override */ {
        boost::contract::old_ptr<std::string> old_str =
                BOOST_CONTRACT_OLDOF(v, str());
        boost::contract::check c = boost::contract::public_function<
                override_put>(
            v,
            // `static_cast` resolves overloaded function pointer ambiguities.
            static_cast<void (string_lines::*)(int, bool,
                    boost::contract::virtual_*)>(&string_lines::put),
            this, x, tab
        )
            .postcondition([&] {
                std::ostringstream s;
                s << x;
                BOOST_CONTRACT_ASSERT(
                        str() == *old_str + (tab ? "\t" : "") + s.str() + '\n');
            })
        ;

        std::ostringstream s;
        s << str_ << (tab ? "\t" : "") << x << '\n';
        str_ = s.str();
    }

private:
    std::string str_;
};

Overloaded functions have the same function name so the same override_function-name type can be reused as template parameter for all boost::contract::public_function calls in a given class. Therefore, BOOST_CONTRACT_OVERRIDE only needs to be invoked once for a function name in a given class, even when that function name is overloaded.

Lambdas, Loops, Code Blocks (and constexpr)
While contracts are usually most useful to program specifications of functions and class interfaces, this library also allows to check contract conditions for implementation code (lambda functions, loops, code blocks, etc.).
Lambda functions are not member functions, they are not part of class public interfaces so they do not check class invariants and they do not subcontract. They can use boost::contract::function to specify preconditions, postconditions, and exception guarantees (considerations made in Non-Member Functions apply). For example (see lambda.cpp):

int total = 0;
std::for_each(v.cbegin(), v.cend(),
    // Contract for a lambda function.
    [&total] (int const x) {
        boost::contract::old_ptr<int> old_total =
                BOOST_CONTRACT_OLDOF(total);
        boost::contract::check c = boost::contract::function()
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(
                        total + x <= std::numeric_limits<int>::max());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(total == *old_total + x);
            })
        ;

        total += x; // Lambda function body.
    }
);

Similarly, boost::contract::function can be used to program preconditions, postconditions, and exception guarantees for loops. For example, for a for-loop but same for while- and all other loops (see loop.cpp):

int total = 0;
// Contract for a for-loop (same for while- and all other loops).
for(std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i) {
    boost::contract::old_ptr<int> old_total = BOOST_CONTRACT_OLDOF(total);
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(
                    total + *i <= std::numeric_limits<int>::max());
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(total == *old_total + *i);
        })
    ;

    total += *i; // For-loop body.
}

More in general, boost::contract::function can be used to program preconditions, postconditions, and exception guarantees of any block of code in a given function. For example (see code_block.cpp):

/* ... */

// Contract for a code block.
{ // Code block entry (check preconditions).
    boost::contract::old_ptr<int> old_total = BOOST_CONTRACT_OLDOF(total);
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(v.size() == 3);
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(total == *old_total + v[0] + v[1] + v[2]);
        })
    ;

    total += v[0] + v[1] + v[2]; // Code block body.
} // Code block exit (check postconditions and exceptions guarantees).

/* ... */

Finally, at the moment this library does not support contracts for functions and classes declared constexpr. [62]
[62] Rationale: In general, it might be useful to specify contracts for constexpr functions and literal classes. However, the implementation of this library cannot support contracts for constexpr functions and classes because C++ does not currently allow constexpr functions to do the following: Declare local variables of (literal) types with non-trivial constexpr destructors (this RAII technique is used by this library to check invariants, postconditions, and exceptions guarantees at exit); Call other constexpr functions using try-catch statements (used by this library to report contract assertion failures and catch any other exception that might be thrown when evaluating the asserted conditions); Use lambda functions (used by this library for convenience to program functors that that check preconditions, postconditions, and exception guarantees). Also note that even if supported, contracts for constexpr functions probably would not use old values (because constexpr prevents functions from having any side effect visible to the caller and variables recording such side-effects are usually the candidates for old value copies) and subcontracting (because constexpr functions cannot be virtual).

Implementation Checks
This library provides a mechanism to check assertions within implementation code a part from preconditions, postconditions, exceptions guarantees, and class invariants. Implementation checks are programmed using a nullary functor that is directly assigned to a boost::contract::check object declaration right at the place within the code where the checks need to be performed (without calling boost::contract::function, boost::contract::public_function, etc. in this case). For example (see check.cpp):

int main() {
    // Implementation checks (via nullary functor).
    boost::contract::check c = [&] {
        BOOST_CONTRACT_ASSERT(gcd(12, 28) == 4);
        BOOST_CONTRACT_ASSERT(gcd(4, 14) == 2);
    };

    return 0;
}

The implementation check functor should capture all the variables that it needs to assert the implementation checks. These variables can be captured by value when the overhead of copying such variables is acceptable. In any case, implementation checks should not modify the value of the captured variables, even when those are captured by reference (see Constant-Correctness).
Any code can be programmed in the implementation check functor, but it is recommended to keep this code simple using mainly assertions and if-statements (to avoid programming complex checks that might be buggy and also slow to check at run-time). It is also recommended to use 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 (this is not a variadic macro, see No Macros):

BOOST_CONTRACT_ASSERT(bool_cond)
// Or, if `bool_cond` contains commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_ASSERT((bool_cond)) // ...use extra parenthesis (not a variadic macro).

This library will automatically call the failure handler boost::contract::check_failure if any of the BOOST_CONTRACT_ASSERT conditions are false and, more in general, if calling the implementation check functor throws any exception. 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.).
Similarly to the C-style assert macro that is disable when NDEBUG is defined, implementation checks are disabled when BOOST_CONTRACT_NO_CHECKS is defined. That will skip all implementation checks at run-time but it will not eliminate some of the overhead of executing and compiling the related boost::contract::check declarations. Alternatively, this library provides the BOOST_CONTRACT_CHECK macro that allows to completely remove run- and compile-time overhead of implementation checks when BOOST_CONTRACT_NO_CHECKS is defined (this is not a variadic macro):

BOOST_CONTRACT_CHECK(bool_cond)
// Or, if `bool_cond` contains commas `,` not already within parenthesis `()`...
BOOST_CONTRACT_CHECK((bool_cond)) // ...use extra parenthesis (not a variadic macro).

For example (see check_macro.cpp):

int main() {
    // Implementation checks (via macro, disable run-/compile-time overhead).
    BOOST_CONTRACT_CHECK(gcd(12, 28) == 4);
    BOOST_CONTRACT_CHECK(gcd(4, 14) == 2);

    return 0;
}

The BOOST_CONTRACT_CHECK macro is similar to the C-style assert macro as it accepts a boolean condition (instead of a nullary functor like boost::contract::check does). [63] Using BOOST_CONTRACT_CHECK is essentially equivalent to using the C-style assert macro a part from the following:
[63] Of course, nothing prevents programmers from calling functors to specify boolean conditions when if-guards and other statements are required to assert the implementation checks. For example, programmers can use C++11 lambda functions to define and call such functors in place where the implementation checks are specified BOOST_CONTRACT_CHECK([...] -> bool { ... } ()).
Implementation checks are disabled defining BOOST_CONTRACT_NO_CHECKS (instead of NDEBUG for disabling assert).
If the asserted boolean condition is either false or it throws an exception then this library will call boost::contract::check_failure (instead assert calls std::abort if the asserted condition is false and unwinds the stack if evaluating the condition throws an exception).
Implementation checks are automatically disabled when other contract conditions specified using this library are already being checked (to avoid infinite recursion, see BOOST_CONTRACT_ALL_DISABLE_NO_ASSERTION).
(See Disable Contract Checking and Disable Contract Compilation for macros to completely remove run- and compile-time overhead also for preconditions, postconditions, exception guarantees, and class invariants.)

Old Value Copies at Body
In the examples seen so far, old value variables of type boost::contract::old_ptr are initialized to a copy of the expression passed to BOOST_CONTRACT_OLDOF as soon as they are declared. This is correctly happens before the function body is executed but also before the contract is declared, therefore even before class invariants (for public functions) and preconditions are checked at function entry. This might work well in most practical cases, however technically old values should be copied before executing the function body but after checking entry class invariants and preconditions (see Assertions). Specifically, there could be cases in which it makes sense to evaluate the expressions passed to BOOST_CONTRACT_OLDOF only under the assumption that assertions programmed in class invariants and preconditions are true.
This library allows to construct boost::contract::old_ptr variables using their default constructor (equivalent to a null pointer) and then to later assign them to a copy of the expression passed to BOOST_CONTRACT_OLDOF in a nullary functor d() passed to .old(d). The functor d() is called by this library before the function body is executed but only after class invariants and preconditions are checked. Old value assignments via .old(...) must appear after preconditions but before postconditions and exception guarantees wen these are all present (see Preconditions, Postconditions, and Exception Guarantees). [64]
[64] Rationale: Functors for preconditions, old value assignments, postconditions, and exception guarantees are all optional but when specified, they must be specified in that order. Such order is enforced by the fact that boost::contract::specify_precondition_old_postcondition_except, boost::contract::specify_old_postcondition_except, boost::contract::specify_postcondition_except, boost::contract::specify_except, and boost::contract::specify_nothing provide a progressively smaller subset of their .precondition(...), .old(...), .postcondition(...), and .except(...) member functions. The enforced order for specifying preconditions, old value assignments, postconditions, and exception guarantees makes logical sense because it follows the order at which these are executed at run-time. Other contract programming frameworks allow to mix this order, that could have been implemented for this library as well but it would have complicated somewhat the library implementation while adding no real value (arguably creating confusion in user code by not enforcing a consistent order for specifying contract conditions).
For example, the following old value expression s[index] passed to BOOST_CONTRACT_OLDOF is valid only after the precondition has checked that index is within valid range index < s.size(). Therefore, old_y is first declared using its default constructor (i.e., initialized to a null pointer) and later assigned to a copy of s[index] in .old(...) after the precondition has checked index (see old.cpp):

char replace(std::string& s, unsigned index, char x) {
    char result;
    boost::contract::old_ptr<char> old_y; // Null, old value copied later...
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(index < s.size());
        })
        .old([&] { // ...after preconditions (and invariants) checked.
            old_y = BOOST_CONTRACT_OLDOF(s[index]);
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(s[index] == x);
            BOOST_CONTRACT_ASSERT(result == *old_y);
        })
    ;

    result = s[index];
    s[index] = x;
    return result;
}

The functor passed to .old(...) should capture all variables it needs to evaluate to copy the old value expressions passed to BOOST_CONTRACT_OLDOF. In general, these variables should be captured by reference and not by value (because old values need to make copies of the values the captured variables will have just before executing the function body, and not copy the values these variables had when the functor passed to .old(...) was first declared). In any case, the functor passed to .old(...) should modify only old values and not the values of other captured variables (see Constant-Correctness).
This library will automatically call the failure handler boost::contract::old_failure if calling the functor specified via .old(...) throws an exception (by default, this handler prints an error message to std::cerr and terminates the program calling std::terminate, but see Throw on Failures to throw exceptions, exit the program with an error code, etc.).
If old value pointers are initialized at the point of their construction instead of using .old(...) then an exception thrown by the old value expression passed to BOOST_CONTRACT_OLDOF, or more in general any exception thrown by the old value pointer initialization, will result in that exception being thrown up the stack by the enclosing function. This is arguably less correct than calling boost::contract::old_failure because an exception thrown by an old value copy causes the program to fail to check its postconditions and exception guarantees but should not automatically causes the enclosing function to thrown an exception (this might not be a significant difference in practice, but it could be an additional reason to use .old(...) instead of assigning old values when they are declared before the contract). [65]
[65] Rationale: It would be possible for this library to internally wrap all old value operations (boost::contract::old_ptr copy constructor, boost::contract::make_old, etc.) with try-catch statements so to call boost::contract::old_failure also when old values are copied when they are constructed outside .old(...). However, that will prevent this library from knowing the boost::contract::from parameter and that would be problematic (specifically because destructors can have postconditions so that parameter is necessary to make sure user-defined failure handlers can be programmed to never throw from destructors as C++ usually requires).

Named Overrides
As seen in Public Function Overrides, the BOOST_CONTRACT_OVERRIDE macro has to be used to declare a type override_... that is passed to boost::contract::public_function for public function overrides. The function names passed to BOOST_CONTRACT_OVERRIDE (and BOOST_CONTRACT_OVERRIDES) should never start with an underscore to avoid generating names containing double underscores override__... (which are reserved by the C++ standard). There is a separate macro BOOST_CONTRACT_NAMED_OVERRIDE that can be used to explicitly specify the name of the type being declared: [66]
[66] Rationale: A different macro BOOST_CONTRACT_NAMED_OVERRIDE is used instead of overloading BOOST_CONTRACT_OVERRIDE using variadic macros because the override macro cannot be programmed manually by users so making it a variadic would prevent to use this library on compilers that do not support variadic macros (see No Macros).

BOOST_CONTRACT_OVERRIDE(func_name)                  // Generate `override_...`.
BOOST_CONTRACT_NAMED_OVERRIDE(type_name, func_name) // Generate `type_name`.

For example, the following public function override is named _1 so BOOST_CONTRACT_OVERRIDE(_1) would declare a type named override__1 (which is reserved in C++ because it contains double underscores __). thus BOOST_CONTRACT_NAMED_OVERRIDE(override1, _1) is used to name the type override1 instead (see named_override.cpp):

template<typename T>
class positive_unary_pack
    #define BASES public generic_unary_pack<T>
    : BASES
{
public:
    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types;
    #undef BASES

    // BOOST_CONTRACT_OVERRIDE(_1) would generate reserved name `override__1`.
    BOOST_CONTRACT_NAMED_OVERRIDE(override1, _1) // Generate `override1`.

    virtual void _1(T const& value, boost::contract::virtual_* v = 0)
            /* override */ {
        // Use `override1` generated by BOOST_CONTRACT_NAMED_OVERRIDE above.
        boost::contract::check c = boost::contract::public_function<override1>(
            v,
            static_cast<void (positive_unary_pack::*)(T const&,
                    boost::contract::virtual_*)>(&positive_unary_pack::_1),
            this,
            value
        )
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(value > 0);
            })
        ;
        value1_ = value;
    }

    /* ... */

The BOOST_CONTRACT_NAMED_OVERRIDE macro can also be used when the name override_... generated by BOOST_CONTRACT_OVERRIDE would clash with other names in user code, to generate names in CamelCase or in any other preferred style, and in any other case when programmers need or prefer to generate names different from override_....
Note that there is not a BOOST_CONTRACT_NAMED_OVERRIDES macro so BOOST_CONTRACT_NAMED_OVERRIDE needs to be invoked separately on each function name (there is instead a BOOST_CONTRACT_OVERRIDES macro as seen in Public Function Overrides). [67]
[67] Rationale: The syntax for invoking a possible BOOST_CONTRACT_NAMED_OVERRIDES macro would need to be something like BOOST_CONTRACT_NAMED_OVERRIDES(type_name1, func_name1, type_name2, func_name2, ...). The authors found such a syntax less readable than repeating single BOOST_CONTRACT_NAMED_OVERRIDE invocations as in BOOST_CONTRACT_NAMED_OVERRIDE(type_name1, func_name1) BOOST_CONTRACT_NAMED_OVERRIDE(type_name2, func_name2) ... so decided not to provide the BOOST_CONTRACT_NAMED_OVERRIDES macro.

Access Specifiers
As we have seen so far, programmers are required to decorate their classes declaring the following extra members that are internally used by this library to check contracts:
The invariant and static_invariant member functions (used to check class invariants, see Class Invariants).
The base_types member type declared via BOOST_CONTRACT_BASE_TYPES (used to implement subcontracting, see Public Function Overrides).
The override_... member types declared via BOOST_CONTRACT_OVERRIDE, BOOST_CONTRACT_NAMED_OVERRIDE, and BOOST_CONTRACT_OVERRIDES (used to implement subcontracting for overriding functions, see Public Function Overrides). [68]
[68] Rationale: The internals of the override_... type generated by BOOST_CONTRACT_OVERRIDE use names reserved by this library so programmers should not actually use such a type even when it is declared public.
In general, these members must be declared public in the user class in order for this library to be able to access them. [69] However, programmers might need to more precisely control the public members of their classes to prevent incorrect access of encapsulated members. All these members can be declared private as long as the boost::contract::access class is declared as friend of the user class. For example (see access.cpp):
[69] There is some variability among compiler implementations: The base_types member type needs to be declared public on MSVC, GCC, and Clang; The invariant and static_invariant member functions need to be declared public on MSVC, but not on GCC and Clang; The override_... member types do not have to be declared public on any compiler. In any case, declaring the boost::contract::access class friend as shown in this section allows to always declare the extra members private on all compilers.

template<typename T>
class vector
    #define BASES public pushable<T>
    : BASES
{
    friend class boost::contract::access; // Friend `access` class so...

    typedef BOOST_CONTRACT_BASE_TYPES(BASES) base_types; // ...private bases.
    #undef BASES

    void invariant() const { // ...private invariants.
        BOOST_CONTRACT_ASSERT(size() <= capacity());
    }

    BOOST_CONTRACT_OVERRIDE(push_back) // ...private overrides.

public:
    void push_back(T const& value, boost::contract::virtual_* v = 0)
            /* override */ {
        boost::contract::old_ptr<unsigned> old_size =
                BOOST_CONTRACT_OLDOF(v, size());
        boost::contract::check c = boost::contract::public_function<
                override_push_back>(v, &vector::push_back, this, value)
            .precondition([&] {
                BOOST_CONTRACT_ASSERT(size() < max_size());
            })
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(size() == *old_size + 1);
            })
        ;

        vect_.push_back(value);
    }

    /* ... */

This technique is not used in most examples of this documentation only for brevity, but programmers are encouraged to use it in real code.
Not declaring boost::contract::access friend of user classes might cause compiler errors on some compilers (e.g., MSVC) because the private members needed to check the contracts will not be accessible. On other compilers (e.g., GCC and Clang), the private access level will instead fail SFINAE and no compiler error will be reported while invariants and subcontracting will be silently skipped at run-time. Therefore, programmers should always make sure to either declare invariant functions and base types typedef as public members or to declare boost::contract::access as friend.

Throw on Failures (and noexcept)
If a condition checked using BOOST_CONTRACT_ASSERT is evaluated to be false or, more in general, if any of the specified contract code throws an exception (BOOST_CONTRACT_ASSERT simply expands to code that throws a boost::contract::assertion_failure exception, see No Macros), this library will call an appropriate contract failure handler function as follow:
Preconditions: False BOOST_CONTRACT_ASSERT assertions and exceptions thrown from within .precondition(...) call boost::contract::precondition_failure.
Postconditions: False BOOST_CONTRACT_ASSERT assertions and exceptions thrown from within .postcondition(...) call boost::contract::postcondition_failure.
Exceptions guarantees: False BOOST_CONTRACT_ASSERT assertions and exceptions thrown from within .except(...) call boost::contract::except_failure.
Class invariants: False BOOST_CONTRACT_ASSERT assertions and exceptions thrown from invariant() and static_invariant() call boost::contract::entry_invariant_failure when checked at function entry and boost::contract::exit_invariant_failure when checked at function exit.
Old value copies at body: Exceptions thrown from old value copies at body within .old(...) call boost::contract::old_failure.
Implementation checks: False BOOST_CONTRACT_ASSERT assertions and exceptions thrown from implementation checks boost::contract::check c = nullary-functor and BOOST_CONTRACT_CHECK(...) call boost::contract::check_failure.
By default, these contract failure handlers print a message to the standard error std::cerr and then terminate the program calling std::terminate. [70] However, programmers can override the default contract failure handlers to perform any custom action on contract failure using the following functions respectively:
[70] Rationale: In general, when a contract fails the only safe thing to do is to terminate program execution (because the contract failure indicates a bug in the program, and in general a buggy program will be in a state for which no operation can be successfully performed, so the program should be stopped as soon as possible). Therefore, this library terminates the program by default. However, for specific applications, programmers could implement some fail-safe mechanism for which some mission-critical operation could always be performed upon handling failures so this library allows programmers to override the default contract failure handlers to fully customize how to handle contract failures.
Preconditions: boost::contract::set_precondition_failure.
Postconditions: boost::contract::set_postcondition_failure.
Exception guarantees: boost::contract::set_except_failure.
Class invariants: boost::contract::set_entry_invariant_failure and boost::contract::set_exit_invariant_failure, or boost::contract::set_invariant_failure (to set both entry and exit invariant failure handlers at once for convenience).
Old value copies at body: boost::contract::set_old_failure.
Implementation checks: boost::contract::set_check_failure.
These set_..._failure(f) function calls return the contract failure handler functor f that they take as input parameter. [71] For example (see throw_on_failure.cpp):
[71] Rationale: The set_..._failure functions take a functor as parameter (to accept not just function pointers but also lambdas, binds, etc.) and they return this same functor as result so they can be concatenated (this interface is a bit different from std::set_terminate). The related get_..._failure functions can be used to query the functors currently set as failure handlers (this interface is similar to std::get_terminate).

int main() {
    boost::contract::set_precondition_failure(
    boost::contract::set_postcondition_failure(
    boost::contract::set_invariant_failure(
    boost::contract::set_old_failure(
        [] (boost::contract::from where) {
            if(where == boost::contract::from_destructor) {
                // Shall not throw from C++ destructors.
                std::clog << "ignored destructor contract failure" << std::endl;
            } else throw; // Re-throw (assertion_failure, user-defined, etc.).
        }
    ))));
    boost::contract::set_except_failure(
        [] (boost::contract::from where) {
            // Already an active exception so shall not throw another...
            std::clog << "ignored exception guarantee failure" << std::endl;
        }
    );
    boost::contract::set_check_failure(
        [] {
            // But now CHECK shall not be used in destructor implementations.
            throw; // Re-throw (assertion_failure, user-defined, etc.).
        }
    );

    /* ... */

When programming custom failure handlers that trow exceptions instead of terminating the program, programmers should be wary of the following:
In order to comply with C++ and STL exception safety, destructors should never throw (in fact destructors are implicitly declared noexcept since C++11). This library passes a boost::contract::from parameter to the contract failure handlers for preconditions, postconditions, class invariants, and old value copies at body (see boost::contract::precondition_failure, boost::contract::postcondition_failure, boost::contract::entry_invariant_failure, boost::contract::exit_invariant_failure, and boost::contract::old_failure respectively). This boost::contract::from parameter indicates if the contract failure occurred in a destructor, constructor, or function call so programmers can use it to code custom contract failure hander functions that never throw from destructors. (In the example above, contract failures from destructors are simply ignored even if that is probably never a safe thing to do in real code.)
C++ stack-unwinding will execute base class destructors even when the derived class destructor trows an exception. Therefore, the contracts of base class destructors will continue to be checked when contract failure handlers are programmed to throw exceptions on contract failures from destructors (yet another reason not to throw exceptions from destructors, not even because of contract failures).
Implementation checks can appear in any code, including destructor implementation code, so boost::contract::check_failure should also never throw, or implementation checks should never be used in destructors otherwise these destructors will throw (note that boost::contract::check_failure does not provide the boost::contract::from parameter so it is not possible to differentiate from implementation checks failing from destructors instead than from other parts of the code).
The contract failure handler for exception guarantees boost::contract::except_failure should never throw (regardless of the value of its boost::contract::from parameter) because when boost::contract::except_failure is called there is already an active exception on the stack, the exception that triggered the exception guarantees to be checked in the first place (throwing an exception while there is already an active exception will force program termination or lead to undefined behaviour in C++).
It is the responsibility of the programmers to decide how to handle contract failures from destructors when they program custom contract failure handlers that throw exceptions instead of terminating the program (given that C++ and STL exception safety rules requires destructors to never throw). This is not a simple dilemma and it might be a good reason to terminate the program instead of throwing exceptions when assertions fail in C++ (as this library and also C-style assert do by default).
Contract assertions can be programmed to throw boost::contract::assertion_failure using BOOST_CONTRACT_ASSERT(condition) as we have seen so far (see No Macros). Alternatively, contract assertions can be programmed to throw any other exception (including user-defined exceptions) using code similar to the following:

if(!condition) throw exception-object;

For example, the following precondition functor throws boost::contract:assertion_failure (via BOOST_CONTRACT_ASSERT) on its first assertion and the user-defined exception too_large_error on its second assertion (both exceptions will cause this library to call the customized boost::contract::precondition_failure listed above which will in turn re-throw the exceptions up he stack, see throw_on_failure.cpp):

struct too_large_error {};

template<unsigned MaxSize>
class cstring
    #define BASES private boost::contract::constructor_precondition<cstring< \
            MaxSize> >
    : BASES
{

public:
    /* implicit */ cstring(char const* chars) :
        boost::contract::constructor_precondition<cstring>([&] {
            BOOST_CONTRACT_ASSERT(chars); // Throw `assertion_failure`.
            // Or, throw user-defined exception.
            if(std::strlen(chars) > MaxSize) throw too_large_error();
        })
    {

    /* ... */
};

Finally, note that the exception specifiers noexcept (since C++11) and throw (deprecated in C++11) of the enclosing operation declaring the contract correctly apply to the contract code as well. Therefore, even if the contract failure handlers are reprogrammed to throw exceptions in case of contract failures, those exceptions will never be thrown outside the context of the enclosing operation if that is not in accordance with the exception specifiers of that operation (specifically, note that all destructors are implicitly declared noexcept in C++11). For example, the following code will correctly never throw from the noexcept destructor, not even if the class invariants checked at destructor entry throw too_large_error and the contract failure handlers for invariants are programmed to throw from destructors (the program will always terminate in this case instead, see throw_on_failure.cpp):

struct too_large_error {};

template<unsigned MaxSize>
class cstring
    #define BASES private boost::contract::constructor_precondition<cstring< \
            MaxSize> >
    : BASES
{

public:
    void invariant() const {
        if(size() > MaxSize) throw too_large_error(); // Throw user-defined ex.
        BOOST_CONTRACT_ASSERT(chars_); // Or, throw `assertion_failure`.
        BOOST_CONTRACT_ASSERT(chars_[size()] == '\0');
    }

    ~cstring() noexcept { // Exception specifiers apply to contract code.
        // Check invariants.
        boost::contract::check c = boost::contract::destructor(this);
    }

    /* ... */
};

/* ... */

// Warning... might cause destructors to throw (unless declared noexcept).
boost::contract::set_invariant_failure(
    [] (boost::contract::from) {
        throw; // Throw no matter if from destructor, etc.
    }
);

/* ... */