{"id":5388,"date":"2018-02-09T17:34:02","date_gmt":"2018-02-09T17:34:02","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-conversions-and-casts\/"},"modified":"2023-06-26T11:57:12","modified_gmt":"2023-06-26T11:57:12","slug":"c-core-guidelines-rules-for-conversions-and-casts","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-for-conversions-and-casts\/","title":{"rendered":"C++ Core Guidelines: Rules for Conversions and Casts"},"content":{"rendered":"<p>What has narrowing conversion and casts in common? They are often the source of errors; therefore, I will write about them today.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5382\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/Metamorphosis_frog_Meyers.png\" alt=\"Metamorphosis frog Meyers\" width=\"500\" height=\"375\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/Metamorphosis_frog_Meyers.png 800w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/Metamorphosis_frog_Meyers-300x225.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/Metamorphosis_frog_Meyers-768x576.png 768w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>Here are the rules from the guidelines.<\/p>\n<ul style=\"margin-top: 0px; margin-bottom: 1rem; color: #515151; font-family: 'PT Sans', Helvetica, Arial, sans-serif; font-size: 20px; font-style: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; background-color: #ffffff;\">\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-narrowing\" style=\"color: #268bd2; text-decoration: none;\">ES.46: Avoid narrowing conversions<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts\" style=\"color: #268bd2; text-decoration: none;\">ES.48: Avoid casts<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts-named\" style=\"color: #268bd2; text-decoration: none;\">ES.49: If you must use a cast, use a named cast<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts-const\" style=\"color: #268bd2; text-decoration: none;\">ES.50: Don\u2019t cast away&nbsp;<code class=\"highlighter-rouge no-highlight\" style=\"font-family: 'Roboto Mono', monospace; padding: 0.2em; font-size: 18px; background-color: #f9f9f9;\">const<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-range-checking\" style=\"color: #268bd2; text-decoration: none;\">ES.55: Avoid the need for range checking<\/a><\/li>\n<\/ul>\n<p>Narrowing conversion is a conversion of a value, including the loss of its precision. Most of the time that is not what you want.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-narrowing\" style=\"color: #268bd2; text-decoration: none;\">ES.46: Avoid narrowing conversions<\/a><\/h3>\n<p>Here are a few examples from the guidelines.<\/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;\">double<\/span> d <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">7.9<\/span>;\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> i <span style=\"color: #555555;\">=<\/span> d;    <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: narrowing: i becomes 7<\/span>\r\ni <span style=\"color: #555555;\">=<\/span> (<span style=\"color: #007788; font-weight: bold;\">int<\/span>) d;  <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: we're going to claim this is still not explicit enough<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x, <span style=\"color: #007788; font-weight: bold;\">long<\/span> y, <span style=\"color: #007788; font-weight: bold;\">double<\/span> d)\r\n{\r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c1 <span style=\"color: #555555;\">=<\/span> x;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: narrowing<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c2 <span style=\"color: #555555;\">=<\/span> y;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: narrowing<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c3 <span style=\"color: #555555;\">=<\/span> d;   <span style=\"color: #0099ff; font-style: italic;\">\/\/ bad: narrowing<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>If you want a narrowing conversion, you should do it explicitly, not implicitly, according to the Python rule from <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0020\/\">The Zen of Python<\/a>:&nbsp; <strong><em>Explicit is better than implicit<\/em>.<\/strong>&nbsp;The guideline support library (GSL) has two casts to express your intent: <span style=\"font-family: 'courier new', courier;\">gsl::narrow_cast<\/span> and <span style=\"font-family: 'courier new', courier;\">gsl::narrow.<\/span><\/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;\">double<\/span> d <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">7.9<\/span>;\r\ni <span style=\"color: #555555;\">=<\/span> narrow_cast<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span>(d);   <span style=\"color: #0099ff; font-style: italic;\">\/\/ OK (you asked for it): narrowing: i becomes 7<\/span>\r\ni <span style=\"color: #555555;\">=<\/span> narrow<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span>(d);        <span style=\"color: #0099ff; font-style: italic;\">\/\/ OK: throws narrowing_error<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The <span style=\"font-family: 'courier new', courier;\">gsl::narrow_cast<\/span> performs the cast, and the <span style=\"font-family: 'courier new', courier;\">gsl::narrow<\/span>&nbsp;cast throws an exception if a narrowing conversion happens.<\/p>\n<p>Most of the time, a narrowing conversion happened secretly. How can you protect yourself from this? Use the power of the curly braces:<\/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: #0099ff; font-style: italic;\">\/\/ suppressNarrowingConversion.cpp<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #007788; font-weight: bold;\">int<\/span> x, <span style=\"color: #007788; font-weight: bold;\">long<\/span> y, <span style=\"color: #007788; font-weight: bold;\">double<\/span> d){\r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c1 <span style=\"color: #555555;\">=<\/span> {x};   \r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c2 <span style=\"color: #555555;\">=<\/span> {y};   \r\n    <span style=\"color: #007788; font-weight: bold;\">char<\/span> c3 <span style=\"color: #555555;\">=<\/span> {d};   \r\n}\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\r\n  <span style=\"color: #007788; font-weight: bold;\">double<\/span> d <span style=\"color: #555555;\">=<\/span> {<span style=\"color: #ff6600;\">7.9<\/span>};         \r\n  <span style=\"color: #007788; font-weight: bold;\">int<\/span> i <span style=\"color: #555555;\">=<\/span> {d};    \r\n\r\n  f(<span style=\"color: #ff6600;\">3<\/span>, <span style=\"color: #ff6600;\">3l<\/span>, <span style=\"color: #ff6600;\">3.0<\/span>);\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>All initializations are put into curly braces. According to the C++11 standard, the compiler has to warn you if a narrowing conversion happens.<span style=\"font-family: 'courier new', courier;\"><\/span><\/p>\n<p>&nbsp;<img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5383\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/narrowingConversion.png\" alt=\"narrowingConversion\" width=\"600\" height=\"206\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/narrowingConversion.png 978w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/narrowingConversion-300x103.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/narrowingConversion-768x264.png 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p><em>Explicit is better than implicit<\/em>. This will not hold a C-cast.<\/p>\n<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts\" style=\"color: #268bd2; text-decoration: none;\">ES.48: Avoid casts<\/a><\/h3>\n<p>Let&#8217;s see what will happen if we screw up the type of system.<\/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: #0099ff; font-style: italic;\">\/\/ casts.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n\r\n  <span style=\"color: #007788; font-weight: bold;\">double<\/span> d <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">2<\/span>;\r\n  <span style=\"color: #006699; font-weight: bold;\">auto<\/span> p <span style=\"color: #555555;\">=<\/span> (<span style=\"color: #007788; font-weight: bold;\">long<\/span><span style=\"color: #555555;\">*<\/span>)<span style=\"color: #555555;\">&amp;<\/span>d;\r\n  <span style=\"color: #006699; font-weight: bold;\">auto<\/span> q <span style=\"color: #555555;\">=<\/span> (<span style=\"color: #007788; font-weight: bold;\">long<\/span> <span style=\"color: #007788; font-weight: bold;\">long<\/span><span style=\"color: #555555;\">*<\/span>)<span style=\"color: #555555;\">&amp;<\/span>d;\r\n  std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> d <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">' '<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #555555;\">*<\/span>p <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">' '<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #555555;\">*<\/span>q <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">'\\n'<\/span>;\r\n  \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Neither the result with the Visual Studio compiler<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5384\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsWin.png\" alt=\"castsWin\" width=\"300\" height=\"85\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsWin.png 320w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsWin-300x85.png 300w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>nor the result with the GCC or the clang compiler is promising.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5385\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsGccClang.png\" alt=\"castsGccClang\" width=\"300\" height=\"42\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsGccClang.png 364w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/castsGccClang-300x42.png 300w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>What is bad about the C-cast? You don&#8217;t see which cast is performed. If you perform a C-cast, a combination of casts will be applied if necessary. Roughly speaking, a C-cast starts with a <span style=\"font-family: 'courier new', courier;\">static_cast<\/span>, continues with a <span style=\"font-family: 'courier new', courier;\">const_cast<\/span>, and finally performs a <span style=\"font-family: 'courier new', courier;\">reinterpret_cast.<\/span><\/p>\n<p>Of course, you know how I will continue: <em>explicit is better than implicit.<\/em><\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts-named\" style=\"color: #268bd2; text-decoration: none;\">ES.49: If you must use a cast, use a named cast<\/a><\/h3>\n<p>Including the GSL, C++ offers eight different named casts. Here are including a short description:<\/p>\n<ul>\n<li><span style=\"font-family: 'courier new', courier;\">static_cast: <\/span>conversion between similar types such as pointer types or numeric types<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">const_cast: <\/span>adds or removes const or volatile&nbsp;<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">reinterpret_cast: <\/span>converts between pointers or between integral types and pointers<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">dynamic_ cast: <\/span>converts between polymorph pointers or references in the same class hierarchy<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">std::move: <\/span>converts to an rvalue reference<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">std::forward: <\/span>converts to an rvalue reference<\/li>\n<li><span style=\"font-family: 'courier new', courier;\">gsl::narrow_cast: applies<\/span>&nbsp;a <span style=\"font-family: 'courier new', courier;\">static_cast<\/span><\/li>\n<li><span style=\"font-family: 'courier new', courier;\">gsl::narrow: applies&nbsp;<\/span>a <span style=\"font-family: 'courier new', courier;\">static_cast<\/span><\/li>\n<\/ul>\n<p>What? <span style=\"font-family: 'courier new', courier;\">std::move<\/span>&nbsp;and <span style=\"font-family: 'courier new', courier;\">std::forward<\/span> are casts? Le&#8217;s have a closer look at the internals of <span style=\"font-family: 'courier new', courier;\">std::move:&nbsp;<\/span><\/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;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>remove_reference<span style=\"color: #555555;\">&lt;decltype(arg)<\/span><span style=\"color: #555555;\">&gt;::<\/span>type<span style=\"color: #555555;\">&amp;&amp;&gt;<\/span>(arg)\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>First, the type of argument <span style=\"font-family: 'courier new', courier;\">arg<\/span> is determined by <span style=\"font-family: 'courier new', courier;\">decltype(arg)<\/span>. Then all references are removed, and two new references are added. The function<span style=\"font-family: 'courier new', courier;\"> std::remove_reference<\/span> is from the type-traits library. I have already written a few posts to the <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/type-traits\">type-traits library.<\/a>&nbsp; In the end, we will always get an rvalue reference.&nbsp;<\/p>\n<p>Casting away <span style=\"font-family: 'courier new', courier;\">const<\/span> is undefined behavior.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-casts-const\" style=\"color: #268bd2; text-decoration: none;\">ES.50: Don\u2019t cast away&nbsp;<code class=\"highlighter-rouge no-highlight\" style=\"font-family: 'Roboto Mono', monospace; padding: 0.2em; font-size: 18px; background-color: #f9f9f9;\">const<\/code><\/a><\/h3>\n<p>Let me be more specific. Casting away const is undefined behavior if the underlying object, such as <span style=\"font-family: 'courier new', courier;\">constInt<\/span> is not mutable.<\/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;\">const<\/span> <span style=\"color: #007788; font-weight: bold;\">int<\/span> constInt <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">10<\/span>;\r\n<span style=\"color: #006699; font-weight: bold;\">const<\/span> <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">*<\/span> pToConstInt <span style=\"color: #555555;\">=<\/span> <span style=\"color: #555555;\">&amp;<\/span>constInt;\r\n \r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">*<\/span> pToInt <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">const_cast<\/span><span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">*&gt;<\/span>(pToConstInt);\r\n<span style=\"color: #555555;\">*<\/span>pToInt <span style=\"color: #555555;\">=<\/span> <span style=\"color: #ff6600;\">12<\/span>;          <span style=\"color: #0099ff; font-style: italic;\">\/\/ undefined behaviour<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>If you don&#8217;t believe me, there is a footnote in the C standard [ISO\/IEC 9899:2011] (subclause 6.7.3, paragraph 4) relevant to the C++ standard:&nbsp;<em>The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.<\/em><\/p>\n<p>Did I mention mutable? <span style=\"font-family: 'courier new', courier;\">mutable<\/span> is one of the unknown features in C++. <span style=\"font-family: 'courier new', courier;\">mutable<\/span> allows you to differentiate between bitwise and logical constness. What?&nbsp;<\/p>\n<p>Imagine you want to implement the interface to a telephone book. For simplicity reasons, the entries should be in a <span style=\"font-family: 'courier new', courier;\">std::unordered_map.<\/span><\/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: #009999;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ teleBook.cpp<\/span><br \/><br \/>#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;unordered_map&gt;<\/span>\r\n\r\nstd<span style=\"color: #555555;\">::<\/span>unordered_map<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string, <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> getUpdatedTelephoneBook(){\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ generate a new, updated telephone book<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> {{<span style=\"color: #cc3300;\">\"grimm\"<\/span>,<span style=\"color: #ff6600;\">123<\/span>}, {<span style=\"color: #cc3300;\">\"huber\"<\/span>, <span style=\"color: #ff6600;\">456<\/span>}, {<span style=\"color: #cc3300;\">\"schmidt\"<\/span>, <span style=\"color: #ff6600;\">321<\/span>}};\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">TelephoneBook<\/span>{\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> getNumber(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> name) <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\r\n        <span style=\"color: #006699; font-weight: bold;\">auto<\/span> ent <span style=\"color: #555555;\">=<\/span> cache.find(name);\r\n        <span style=\"color: #006699; font-weight: bold;\">if<\/span>(ent <span style=\"color: #555555;\">!=<\/span> cache.end()){                              \r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> ent<span style=\"color: #555555;\">-&gt;<\/span>second;\r\n        }\r\n        <span style=\"color: #006699; font-weight: bold;\">else<\/span>{\r\n            cache <span style=\"color: #555555;\">=<\/span> getUpdatedTelephoneBook();               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> cache[name];\r\n        }\r\n    }\r\n<span style=\"color: #9999ff;\">private:<\/span>                                                     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>unordered_map<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string, <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> cache <span style=\"color: #555555;\">=<\/span> {{<span style=\"color: #cc3300;\">\"grimm\"<\/span>,<span style=\"color: #ff6600;\">123<\/span>}, {<span style=\"color: #cc3300;\">\"huber\"<\/span>, <span style=\"color: #ff6600;\">456<\/span>}};\r\n};\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    TelephoneBook telBook;                                   <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"grimm \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> telBook.getNumber(<span style=\"color: #cc3300;\">\"grimm\"<\/span>) <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"schmidt \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> telBook.getNumber(<span style=\"color: #cc3300;\">\"schmidt\"<\/span>) <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>My telephone book (1) is tiny. Usually, a telephone book is quite big, and updating it is quite expensive (2). This means updating a printed telephone book will happen only once a year in Germany. From the conceptional view, the inquiries to the <span style=\"font-family: 'courier new', courier;\">teleBook<\/span> (3) should be <span style=\"font-family: 'courier new', courier;\">const.<\/span> <span>This is not&nbsp;possible because the <span style=\"font-family: 'courier new', courier;\">unordered_map<\/span> is modified in the method <span style=\"font-family: 'courier new', courier;\">getNumber<\/span>. Here is the proof in red ellipses.<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5386\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBookError.png\" alt=\"telephoneBookError\" width=\"600\" height=\"221\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBookError.png 1210w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBookError-300x110.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBookError-1024x377.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBookError-768x282.png 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/>&nbsp;<\/p>\n<p>The qualifier<span style=\"font-family: 'courier new', courier;\"> mutable<\/span> allows you to differentiate between bitwise and logical constness. The <span style=\"font-family: 'courier new', courier;\">telBook<\/span> is logical but not bitwise const.&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: #009999;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ teleBook.cpp<\/span><br \/><br \/>#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;unordered_map&gt;<\/span>\r\n\r\nstd<span style=\"color: #555555;\">::<\/span>unordered_map<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string, <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> getUpdatedTelephoneBook(){\r\n    <span style=\"color: #0099ff; font-style: italic;\">\/\/ generate a new, updated telephone book<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">return<\/span> {{<span style=\"color: #cc3300;\">\"grimm\"<\/span>,<span style=\"color: #ff6600;\">123<\/span>}, {<span style=\"color: #cc3300;\">\"huber\"<\/span>, <span style=\"color: #ff6600;\">456<\/span>}, {<span style=\"color: #cc3300;\">\"schmidt\"<\/span>, <span style=\"color: #ff6600;\">321<\/span>}};\r\n}\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">class<\/span> <span style=\"color: #00aa88; font-weight: bold;\">TelephoneBook<\/span>{\r\n<span style=\"color: #9999ff;\">public:<\/span>\r\n    <span style=\"color: #007788; font-weight: bold;\">int<\/span> getNumber(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> name) <span style=\"color: #006699; font-weight: bold;\">const<\/span> {\r\n        <span style=\"color: #006699; font-weight: bold;\">auto<\/span> ent <span style=\"color: #555555;\">=<\/span> cache.find(name);\r\n        <span style=\"color: #006699; font-weight: bold;\">if<\/span>(ent <span style=\"color: #555555;\">!=<\/span> cache.end()){                              \r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> ent<span style=\"color: #555555;\">-&gt;<\/span>second;\r\n        }\r\n        <span style=\"color: #006699; font-weight: bold;\">else<\/span>{\r\n            cache <span style=\"color: #555555;\">=<\/span> getUpdatedTelephoneBook();               <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n            <span style=\"color: #006699; font-weight: bold;\">return<\/span> cache[name];\r\n        }\r\n    }\r\n<span style=\"color: #9999ff;\">private:<\/span>                                                     <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    <span style=\"color: #006699; font-weight: bold;\">mutable<\/span> std<span style=\"color: #555555;\">::<\/span>unordered_map<span style=\"color: #555555;\">&lt;<\/span>std<span style=\"color: #555555;\">::<\/span>string, <span style=\"color: #007788; font-weight: bold;\">int<\/span><span style=\"color: #555555;\">&gt;<\/span> cache <span style=\"color: #555555;\">=<\/span> {{<span style=\"color: #cc3300;\">\"grimm\"<\/span>,<span style=\"color: #ff6600;\">123<\/span>}, {<span style=\"color: #cc3300;\">\"huber\"<\/span>, <span style=\"color: #ff6600;\">456<\/span>}};\r\n};\r\n\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    <span style=\"color: #006699; font-weight: bold;\">const<\/span> TelephoneBook telBook;                             <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"grimm \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> telBook.getNumber(<span style=\"color: #cc3300;\">\"grimm\"<\/span>) <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\"schmidt \"<\/span> <span style=\"color: #555555;\">&lt;&lt;<\/span> telBook.getNumber(<span style=\"color: #cc3300;\">\"schmidt\"<\/span>) <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I just added <span style=\"font-family: 'courier new', courier;\">const<\/span> (3) to the telBook and <span style=\"font-family: 'courier new', courier;\">mutable<\/span> to the cache (1), and the program behaves as expected.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5387\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBook.png\" alt=\"telephoneBook\" width=\"300\" height=\"155\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBook.png 415w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2018\/02\/telephoneBook-300x155.png 300w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/>&nbsp;<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Res-range-checking\" style=\"color: #268bd2; text-decoration: none;\">ES.55: Avoid the need for range checking<\/a><\/h3>\n<p>I can make it short. By using the range-based for-loop or algorithms of the STL, there is no need to check the range.<\/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%;\">std<span style=\"color: #555555;\">::<\/span>array<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">int<\/span>, <span style=\"color: #ff6600;\">10<\/span><span style=\"color: #555555;\">&gt;<\/span> arr <span style=\"color: #555555;\">=<\/span> {<span style=\"color: #ff6600;\">5<\/span>, <span style=\"color: #ff6600;\">7<\/span>, <span style=\"color: #ff6600;\">4<\/span>, <span style=\"color: #ff6600;\">2<\/span>, <span style=\"color: #ff6600;\">8<\/span>, <span style=\"color: #ff6600;\">6<\/span>, <span style=\"color: #ff6600;\">1<\/span>, <span style=\"color: #ff6600;\">9<\/span>, <span style=\"color: #ff6600;\">0<\/span>, <span style=\"color: #ff6600;\">3<\/span>}; \r\nstd<span style=\"color: #555555;\">::<\/span>sort(arr.begin(), arr.end());\r\n<span style=\"color: #006699; font-weight: bold;\">for<\/span> (<span style=\"color: #006699; font-weight: bold;\">auto<\/span> a <span style=\"color: #555555;\">:<\/span> arr) {\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> a <span style=\"color: #555555;\">&lt;&lt;<\/span> <span style=\"color: #cc3300;\">\" \"<\/span>;\r\n}   \r\n<span style=\"color: #0099ff; font-style: italic;\">\/\/ 0 1 2 3 4 5 6 7 8 9<\/span>\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>In the <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-do-s-and-don-ts\">next post<\/a> on expressions, I will write about <span style=\"font-family: 'courier new', courier;\">std::move<\/span>, <span style=\"font-family: 'courier new', courier;\">new<\/span> and <span style=\"font-family: 'courier new', courier;\">delete<\/span>, and slicing. Slicing is probably one of the darkest corners of C++. So, stay tuned.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What has narrowing conversion and casts in common? They are often the source of errors; therefore, I will write about them today.<\/p>\n","protected":false},"author":21,"featured_media":5382,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[474],"class_list":["post-5388","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-conversions"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5388","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=5388"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5388\/revisions"}],"predecessor-version":[{"id":6840,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5388\/revisions\/6840"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5382"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5388"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5388"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5388"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}