{"id":5475,"date":"2018-07-20T12:24:18","date_gmt":"2018-07-20T12:24:18","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-a-detour-to-contracts\/"},"modified":"2023-06-26T11:47:40","modified_gmt":"2023-06-26T11:47:40","slug":"c-core-guidelines-a-detour-to-contracts","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-a-detour-to-contracts\/","title":{"rendered":"C++ Core Guidelines: A Short Detour to Contracts in C++20"},"content":{"rendered":"<p>My original plan was it to write in this post about the next rules to error handling. But I changed my plan to write about the future: contracts in C++20.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5473\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/07\/Design_by_contract.png\" alt=\"Design by contract\" style=\"display: block; margin-left: auto; margin-right: auto;\" width=\"490\" height=\"480\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/07\/Design_by_contract.png 490w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/07\/Design_by_contract-300x294.png 300w\" sizes=\"auto, (max-width: 490px) 100vw, 490px\" \/><\/p>\n<p style=\"text-align: center;\">By <a href=\"https:\/\/it.wikipedia.org\/wiki\/Fabuio\" class=\"extiw\" title=\"it:Fabuio\">Fabuio<\/a> &#8211; <span class=\"int-own-work\" lang=\"en\">Own work<\/span>, <a href=\"http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/deed.en\" title=\"Creative Commons Zero, Public Domain Dedication\">CC0<\/a>, <a href=\"https:\/\/commons.wikimedia.org\/w\/index.php?curid=38020523\">Link<\/a><\/p>\n<p>Here are the rules I will skip.<\/p>\n<ul>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-design-invariants\">E.4: Design your error-handling strategy around invariants<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-invariant\">E.5: Let a constructor establish an invariant, and throw if it cannot<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-raii\">E.6: Use RAII to prevent leaks<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-precondition\">E.7: State your preconditions<\/a><\/li>\n<li>\n<p><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Re-postcondition\">E.8: State your postconditions<\/a><\/p>\n<\/li>\n<\/ul>\n<p>Why did I change my plan? I did it for a few reasons.<\/p>\n<ul>\n<li>The cited rules for error handling in the C++ core guidelines do not have enough meat.<\/li>\n<li>I wrote about rule E.6 in a post: <a href=\"https:\/\/www.modernescpp.com\/index.php\/garbage-collectio-no-thanks\">Garbage Collection &#8211; No Thanks<\/a>. Of course, I don&#8217;t want to repeat myself.<\/li>\n<li>Four of the five rules are about <a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_by_contract\">design by contract. <\/a><\/li>\n<\/ul>\n<p>The consequence of these points is quite simple. Contracts seem necessary for error handling; C++20 will presumably have contracts. Therefore, I am writing this post about contracts in C++20.<\/p>\n<p>In case you want to have more details on contracts. This post is based on proposals <a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2016\/p0380r1.pdf\">P0380R1 <\/a>and <a href=\"http:\/\/open-std.org\/JTC1\/SC22\/WG21\/docs\/papers\/2018\/p0542r5.html\">P0542R5<\/a>.<\/p>\n<p>First of all.<\/p>\n<h3>What is a contract?<\/h3>\n<p>A contract specifies in a precise and checkable way interfaces for software components. These software components are functions and methods that must fulfill preconditions, postconditions, and invariants. Here are the shortened definitions from the proposals.<\/p>\n<ul>\n<li>A <strong>precondition<\/strong>: a predicate that is supposed to hold upon entry in a function. It is placed outside the function definition.<\/li>\n<li>A <strong>postcondition<\/strong>: a predicate that is supposed to hold upon exit from the function. It is placed outside the function definition.<\/li>\n<li>An <strong>assertion<\/strong>: a predicate that is supposed to hold at its point in the computation. It is placed inside the function definition.<\/li>\n<\/ul>\n<p>The precondition and the postcondition are in C++20, placed outside the function definition, but the invariant is placed inside the function definition. A predicate is a function that returns a boolean.<\/p>\n<div>\n<div>&nbsp;<\/div>\n<div>Here is a first example:<\/div>\n<\/div>\n<div>&nbsp;<\/div>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">int<\/span> push(queue<span style=\"color: #555555;\">&amp;<\/span> q, int val) \r\n  [[ expects<span style=\"color: #555555;\">:<\/span> !q<span style=\"color: #555555;\"><\/span>.full() ]]\r\n  [[ ensures <span style=\"color: #555555;\">!<\/span>q.empty() ]]{\r\n  ...\r\n  [[assert<span style=\"color: #555555;\">:<\/span> q.is_ok() ]]<br \/>  ...\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The attribute <span style=\"font-family: courier new, courier;\">expects<\/span>&nbsp;is a precondition, the attribute <span style=\"font-family: courier new, courier;\">ensures<\/span>&nbsp;is a postcondition, and the attribute <span style=\"font-family: courier new, courier;\">assert&nbsp;<\/span>is an assertion.<\/p>\n<p>The contracts for the function <span style=\"font-family: courier new, courier;\">push<\/span>&nbsp;are that the queue is incomplete before adding an element that is not empty after adding, and the assertion <span style=\"font-family: courier new, courier;\">q.is_ok()<\/span> holds.<\/p>\n<p>Preconditions and postconditions are part of the function interface. This means they can&#8217;t access local members of a function or private or protected members of a class. In contrast, assertions are part of the implementation and can, therefore, access local members of a function of private or protected class members.<\/p>\n<p>&nbsp;<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">X<\/span> {\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(<span style=\"color: #007788; font-weight: bold;\">int<\/span> n)\r\n        [[ expects<span style=\"color: #555555;\">:<\/span> n<span style=\"color: #555555;\">&lt;<\/span>m ]]  <span style=\"color: #0099ff; font-style: italic;\">\/\/ error; m is private<\/span>\r\n    {\r\n        [[ assert<span style=\"color: #555555;\">:<\/span> n<span style=\"color: #555555;\">&lt;<\/span>m ]];  <span style=\"color: #0099ff; font-style: italic;\">\/\/ OK<\/span>\r\n        <span style=\"color: #0099ff; font-style: italic;\">\/\/ ...<\/span>\r\n    }\r\n<span style=\"color: #9999ff;\">private:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> m;\r\n};     \r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><span style=\"font-family: courier new, courier;\">m<\/span> is private and can not be part of a precondition.<\/p>\n<p>By default, a violation of a contract terminates the program. This is not the whole story; let me give you more details.<\/p>\n<\/p>\n<h3>More Details<\/h3>\n<p>Here is the full syntax of the contract attributes:<span style=\"font-family: courier new, courier;\"><strong> [[contract-attribute modifier: conditional-expression ]]<\/strong><\/span><\/p>\n<ul>\n<li><strong><span style=\"font-family: courier new, courier;\">contract-attribute<\/span><\/strong>: <span style=\"font-family: courier new, courier;\">expects,<\/span> <span style=\"font-family: courier new, courier;\">ensures,<\/span> and <span style=\"font-family: courier new, courier;\">assert<\/span><\/li>\n<li><strong><span style=\"font-family: courier new, courier;\">modifier:<\/span><\/strong> specifies the contract level or the enforcement of the contract; possible values are <span style=\"font-family: courier new, courier;\">default, audit, <\/span><span style=\"font-family: courier new, courier;\"><\/span>and <span style=\"font-family: courier new, courier;\">axiom<\/span>\n<ul>\n<li><span style=\"font-family: courier new, courier;\">default: <\/span>the cost of run-time checking should be small; it is the default modifier<\/li>\n<li><span style=\"font-family: courier new, courier;\">audit:<\/span> the cost of run-time checking is assumed to be large<\/li>\n<li><span style=\"font-family: courier new, courier;\">axiom:<\/span> the predicate is not checked at run-time<\/li>\n<\/ul>\n<\/li>\n<li><strong><span style=\"font-family: courier new, courier;\">conditional-expression<\/span><\/strong>: the predicate of the contract<\/li>\n<\/ul>\n<p>For the <span style=\"font-family: 'courier new', courier;\">ensures<\/span> attribute, there is an additional identifier available. <strong>[[ensures modifier identifier: conditional-expression ]]<\/strong><span style=\"font-family: courier new, courier;\"><\/span><\/p>\n<p>The <span style=\"font-family: 'courier new', courier;\"><strong>identifier<\/strong><\/span> lets you refer to the return value of the function.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">int<\/span> mul(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x, <span style=\"color: #007788; font-weight: bold;\">int<\/span> y)\r\n  [[expects<span style=\"color: #555555;\">:<\/span> x <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>]]         \/\/ implicit default\r\n  [[expects <span style=\"color: #006699; font-weight: bold;\">default<\/span><span style=\"color: #555555;\">:<\/span> y <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>]]\r\n  [[ensures audit res<span style=\"color: #555555;\">:<\/span> res <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>]]{\r\n  <span style=\"color: #006699; font-weight: bold;\">return<\/span> x <span style=\"color: #555555;\">*<\/span> y;\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><span style=\"font-family: courier new, courier;\">res<\/span>&nbsp;as the identifier is, in this case, an arbitrary name. As shown in the example, you can use more contracts of the same kind.<\/p>\n<p>Let me dive deeper into the modifiers and the handling of the contract violations.<\/p>\n<h3>Handling contract violations<\/h3>\n<p>A compilation has three assertion build levels:<\/p>\n<ul>\n<li><strong>off:<\/strong> no contracts are checked<\/li>\n<li><strong>default:<\/strong> default contracts are checked; this is the default<\/li>\n<li><strong>audit:<\/strong> default and audit contracts are checked<\/li>\n<\/ul>\n<p>If a contract violation occurs &#8211; the predicate evaluates to false -, the violation handler is invoked. The violation handler is a function of type <span style=\"font-family: courier new, courier;\">noexcept<\/span> which takes a <span style=\"font-family: courier new, courier;\">const std::contract_violation<\/span> and returns a <span style=\"font-family: courier new, courier;\">void. <\/span>Because the function is noexcept,<span style=\"font-family: courier new, courier;\"> <\/span>this means that <span style=\"font-family: courier new, courier;\">std::terminate<\/span> is called in case of a contract violation. A user can set a violation handler.<\/p>\n<p>The class <span style=\"font-family: courier new, courier;\">std::contract_violation<\/span> gives information about the violation of the contract.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">namespace<\/span> std{ \r\n  <span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">contract_violation<\/span>{\r\n  <span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">uint_least32_t<\/span> line_number() <span style=\"color: #006699; font-weight: bold;\">const<\/span> noexcept;\r\n    string_view file_name() <span style=\"color: #006699; font-weight: bold;\">const<\/span> noexcept;\r\n    string_view function_name() <span style=\"color: #006699; font-weight: bold;\">const<\/span> noexcept;\r\n    string_view comment() <span style=\"color: #006699; font-weight: bold;\">const<\/span> noexcept;\r\n    string_view assertion_level() <span style=\"color: #006699; font-weight: bold;\">const<\/span> noexcept;\r\n  };\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<ul>\n<li><span style=\"font-family: courier new, courier;\">line_number: <\/span>the line number of the contract violation<span style=\"font-family: courier new, courier;\"><br \/><\/span><\/li>\n<li><span style=\"font-family: courier new, courier;\">file_name: <\/span>the filename of the contract violation<span style=\"font-family: courier new, courier;\"><br \/><\/span><\/li>\n<li><span style=\"font-family: courier new, courier;\">function_name: <\/span>function name of the contract violation<span style=\"font-family: courier new, courier;\"><br \/><\/span><\/li>\n<li><span style=\"font-family: courier new, courier;\">comment: <\/span>the predicate to the contract<span style=\"font-family: courier new, courier;\"><br \/><\/span><\/li>\n<li><span style=\"font-family: courier new, courier;\">assertion_level: <\/span>assertion level to the contract<span style=\"font-family: courier new, courier;\"><br \/><\/span><\/li>\n<\/ul>\n<p>&nbsp;There are a few rules to remember if you declare a contract.<\/p>\n<h3>Declaration of contracts<\/h3>\n<p>A contract can be placed on the declaration of a function. This includes declarations of virtual functions or function templates.<\/p>\n<ul>\n<li>The contract declaration of a function must be identical. Any declaration different from the first one can omit the contract.<\/li>\n<\/ul>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">int<\/span> f(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x) \r\n  [[expects<span style=\"color: #555555;\">:<\/span> x<span style=\"color: #555555;\">&gt;<\/span><span style=\"color: #ff6600;\">0<\/span>]]\r\n  [[ensures r<span style=\"color: #555555;\">:<\/span> r<span style=\"color: #555555;\">&gt;<\/span><span style=\"color: #ff6600;\">0<\/span>]];\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x); <span style=\"color: #0099ff; font-style: italic;\">\/\/ OK. No contract.<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> f(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x)\r\n  [[expects<span style=\"color: #555555;\">:<\/span> x<span style=\"color: #555555;\">&gt;=<\/span><span style=\"color: #ff6600;\">0<\/span>]]; <span style=\"color: #0099ff; font-style: italic;\">\/\/ Error missing ensures and different expects condition<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<ul>\n<li>A contract can not be modified in an overriding function.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #006699; font-weight: bold;\">struct<\/span> B{\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x)[[expects<span style=\"color: #555555;\">:<\/span> x <span style=\"color: #555555;\">&gt;<\/span> <span style=\"color: #ff6600;\">0<\/span>]];\r\n  <span style=\"color: #006699; font-weight: bold;\">virtual<\/span> <span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">g<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x);\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> D<span style=\"color: #555555;\">:<\/span> B{\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> f(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x)[[expects<span style=\"color: #555555;\">:<\/span> x <span style=\"color: #555555;\">&gt;=<\/span> <span style=\"color: #ff6600;\">0<\/span>]];   <span style=\"color: #0099ff; font-style: italic;\">\/\/ error<\/span>\r\n  <span style=\"color: #007788; font-weight: bold;\">void<\/span> g(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x)[[expects<span style=\"color: #555555;\">:<\/span> x <span style=\"color: #555555;\">!=<\/span> <span style=\"color: #ff6600;\">0<\/span>]];   <span style=\"color: #0099ff; font-style: italic;\">\/\/ error<\/span>\r\n};\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Both contract definitions of class <span style=\"font-family: courier new, courier;\">D<\/span> are erroneous. The contract of the method <span style=\"font-family: courier new, courier;\">f<\/span> differs from the one from <span style=\"font-family: courier new, courier;\">B::f<\/span>. The method <span style=\"font-family: courier new, courier;\">D::g<\/span> adds a contract to <span style=\"font-family: courier new, courier;\">B::g<\/span>.<\/p>\n<h3>Closing Thoughts<\/h3>\n<p>Impressed? Me too! I still can not imagine how fundamentally contracts will change how we write functions and think about interfaces and exception handling. Maybe Herb Sutter&#8217;s thoughts on <a href=\"https:\/\/herbsutter.com\/2018\/07\/02\/trip-report-summer-iso-c-standards-meeting-rapperswil\/\">Sutter&#8217;s Mill<\/a> give you an idea because, for him, &#8220;<em>contracts is the most impactful feature of C++20 so far, and arguably the most impactful feature we have added to C++ since C++11<\/em>.&#8221;<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>With my next post, I will continue with a step back to the present time and write about the rules for exception handling.<\/p>\n<h2>Further Information<\/h2>\n<p>&nbsp;Wow! Almost 200 readers participated in the vote for the next pdf bundle. Here are the winners.<\/p>\n<div class=\"text\">\n<ul>\n<li>German pdf bundle: Embedded: Performanz z\u00e4hlt<\/li>\n<li>English pdf bundle: C++ Core Guidelines: Concurrency and Parallelism<\/li>\n<\/ul>\n<\/div>\n<div class=\"text\">Here are the details of the vote:<\/div>\n<div class=\"text\">\n<ul>\n<li>German blog: <a href=\"https:\/\/www.grimm-jaud.de\/index.php\/blog\/welches-pdf-paeckchen-soll-ich-zusammenstellen-mache-dein-kreuz-4\">Welches PDF-P\u00e4ckchen soll ich zusammenstellen? Mache dein Kreuz!<\/a><\/li>\n<li>English Blog: <a href=\"https:\/\/www.modernescpp.com\/index.php\/which-pdf-bundle-should-i-provide-make-your-choice-3\">Which PDF bundle should I provide? Make your choice!<\/a><\/li>\n<\/ul>\n<p>I need at least a week to proofread and prepare the pdf bundles<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>My original plan was it to write in this post about the next rules to error handling. But I changed my plan to write about the future: contracts in C++20.<\/p>\n","protected":false},"author":21,"featured_media":5473,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[481,478,482],"class_list":["post-5475","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-contracts","tag-error-handling","tag-outdated"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5475","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5475"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5475\/revisions"}],"predecessor-version":[{"id":6818,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5475\/revisions\/6818"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5473"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5475"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5475"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5475"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}