{"id":5103,"date":"2016-12-26T18:03:50","date_gmt":"2016-12-26T18:03:50","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/garbage-collectio-no-thanks\/"},"modified":"2023-06-26T12:29:46","modified_gmt":"2023-06-26T12:29:46","slug":"garbage-collectio-no-thanks","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/garbage-collectio-no-thanks\/","title":{"rendered":"Garbage Collection &#8211; No Thanks"},"content":{"rendered":"<p>C++ is old-fashioned. C++ has no garbage collection. No garbage collection? Right! Old fashioned? Wrong!<\/p>\n<p><!--more--><\/p>\n<p>What is against garbage collection in C++? At first, garbage collection breaks one of the key principles of C++: &#8220;Don&#8217;t pay for something you don&#8217;t use.&#8221; That means if you don&#8217;t need garbage collection your C++ runtime should not waste its time cleaning up the whole garbage. My second point is more sophisticated.<\/p>\n<p>We have RAII in C++ and therefore the deterministic destruction of objects. But, what is RAII? That&#8217;s the topic of this post.<\/p>\n<h2><strong>R<\/strong>esource <strong>A<\/strong>cquisition <strong>I<\/strong>s <strong>I<\/strong>nitialization<\/h2>\n<p>RAII stand for <strong>R<\/strong>esource <strong>A<\/strong>cquisition <strong>I<\/strong>s <strong>I<\/strong>nitialization. Probably, the most important idiom in C++ says that a resource should be acquired in the constructor of the object and released in the destructor of the object. The key is that the destructor will be automatically called if the object goes out of scope. If this is not totally deterministic? In Java or Python (<span style=\"font-family: courier new,courier;\">__del__<\/span>) you have a destructor but not the guarantee. Therefore, it can end disastrous, if you use the destructor to release a critical resource like a lock. That&#8217;s a classical anti-pattern for a deadlock. But in C++, we are on the safe side.<\/p>\n<p>The example shows the totally deterministic behavior of RAII in C++.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"> 1\r\n 2\r\n 3\r\n 4\r\n 5\r\n 6\r\n 7\r\n 8\r\n 9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31\r\n32\r\n33\r\n34\r\n35\r\n36\r\n37\r\n38\r\n39\r\n40\r\n41\r\n42\r\n43\r\n44\r\n45\r\n46<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008000;\">\/\/ raii.cpp<\/span>\r\n\r\n<span style=\"color: #0000ff;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;new&gt;<\/span>\r\n<span style=\"color: #0000ff;\">#include &lt;string&gt;<\/span>\r\n\r\n<span style=\"color: #0000ff;\">class<\/span> <span style=\"color: #2b91af;\">ResourceGuard<\/span>{\r\n  private:\r\n    <span style=\"color: #0000ff;\">const<\/span> std::string resource;\r\n  public:\r\n    ResourceGuard(<span style=\"color: #0000ff;\">const<\/span> std::string&amp; res):resource(res){\r\n      std::cout &lt;&lt; <span style=\"color: #a31515;\">\"Acquire the \"<\/span> &lt;&lt; resource &lt;&lt; <span style=\"color: #a31515;\">\".\"<\/span> &lt;&lt;  std::endl;\r\n    }\r\n    ~ResourceGuard(){\r\n      std::cout &lt;&lt; <span style=\"color: #a31515;\">\"Release the \"<\/span>&lt;&lt; resource &lt;&lt; <span style=\"color: #a31515;\">\".\"<\/span> &lt;&lt; std::endl;\r\n    }\r\n};\r\n\r\n<span style=\"color: #2b91af;\">int<\/span> main(){\r\n\r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  ResourceGuard resGuard1{<span style=\"color: #a31515;\">\"memoryBlock1\"<\/span>};\r\n\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"\\nBefore local scope\"<\/span> &lt;&lt; std::endl;\r\n  {\r\n    ResourceGuard resGuard2{<span style=\"color: #a31515;\">\"memoryBlock2\"<\/span>};\r\n  }\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"After local scope\"<\/span> &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n\r\n  \r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"\\nBefore try-catch block\"<\/span> &lt;&lt; std::endl;\r\n  try{\r\n      ResourceGuard resGuard3{<span style=\"color: #a31515;\">\"memoryBlock3\"<\/span>};\r\n      <span style=\"color: #0000ff;\">throw<\/span> std::bad_alloc();\r\n  }   \r\n  <span style=\"color: #0000ff;\">catch<\/span> (std::bad_alloc&amp; e){\r\n      std::cout &lt;&lt; e.what();\r\n  }\r\n  std::cout &lt;&lt; <span style=\"color: #a31515;\">\"\\nAfter try-catch block\"<\/span> &lt;&lt; std::endl;\r\n  \r\n  std::cout &lt;&lt; std::endl;\r\n\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p><span style=\"font-family: courier new,courier;\">ResourceGuard<\/span> is a guard that managed its resource. In this case, the resource is a simple string. <span style=\"font-family: courier new,courier;\">ResourceGuard<\/span> creates in its constructor (line 11 &#8211; 13) the resource and releases the resource in its destructor (line 14 &#8211; 16). It does its job very reliable.<\/p>\n<p>The destructor of <span style=\"font-family: courier new,courier;\">resGuard1<\/span> (line 23) will be exactly called at the end of the <span style=\"font-family: courier new,courier;\">main<\/span> function (line 46). The lifetime of <span style=\"font-family: courier new,courier;\">resGuard2<\/span> (line 27) already ends in line 28. Therefore, the destructor will automatically be executed. Even the throwing of an exception does not alter the reliability of <span style=\"font-family: courier new,courier;\">resGuard3<\/span> (line 36). Its destructor will be called at the end of the <span style=\"font-family: courier new,courier;\">try<\/span> block (line 35 &#8211; 38).<\/p>\n<p>The screenshot displays the lifetime of the objects.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5101\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/raii.png\" alt=\"raii\" style=\"margin: 15px;\" width=\"456\" height=\"372\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/raii.png 456w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/raii-300x245.png 300w\" sizes=\"auto, (max-width: 456px) 100vw, 456px\" \/><\/p>\n<p>I will refer once more to the program <span style=\"font-family: courier new,courier;\">raii.cpp.<\/span> What is the key idea of the RAII idiom? <strong>The lifetime of a resource will be bound to the lifetime of a local variable. C++ automatically manages the lifetime of locals.<\/strong><\/p>\n<p>The idea is quite simple but has far-reaching consequences. Critical resources are bound to local objects. The remaining job is done by the C++ runtime.<\/p>\n<h3>RAII everywhere<\/h3>\n<p>RAII everywhere holds for locks&nbsp; <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/lock\">std::lock_guard, std::unique_lock, <\/a>and <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/lock\">std::shared_lock<\/a>&nbsp; that manage their resource mutex. RAII everywhere holds for the smart pointers <a href=\"https:\/\/www.modernescpp.com\/index.php\/std-unique-ptr\">std::unique_ptr<\/a>, <a href=\"https:\/\/www.modernescpp.com\/index.php\/std-shared-ptr\">std::shared_ptr<\/a>, and <a href=\"https:\/\/www.modernescpp.com\/index.php\/std-weak-ptr\">std::weak_ptr <\/a>that manage their resource memory.<\/p>\n<p>Thanks to RAII we have in C++ a kind of garbage collection.<\/p>\n<p>But there is a subtle difference to a general garbage collection.<\/p>\n<ol>\n<li>You have to explicitly use smart pointers in C++<\/li>\n<li>The memory management with&nbsp; <span style=\"font-family: courier new,courier;\">std::unique_ptr<\/span> has by design no overhead in performance or memory compared to a raw pointer (see <a href=\"https:\/\/www.modernescpp.com\/index.php\/memory-and-performance-overhead-of-smart-pointer\">Memory and Performance Overhead of Smart Pointers<\/a>).<\/li>\n<\/ol>\n<p>Therefore, C++ adheres to its key principle in a twofold way: Don&#8217;t pay for something you don&#8217;t use.<\/p>\n<\/p>\n<h2>Special resources<\/h2>\n<p>Thanks to RAII, the destructor of the local object and therefore the cleaning up of the resource will be done totally deterministic. So far, so good. If the destructor can throw an exception, the destructor of the object modeling RAII will trigger the exception. This will be the case if the resource is a file. The <span style=\"font-family: courier new,courier;\">close<\/span> function can trigger an exception. Therefore, you have to answer the question for yourself, if it&#8217;s ok, that the destructor can throw an exception. If not, you should not use RAII.<\/p>\n<h3>Dealing with throwing destructors (<strong>Udo Steinbach<\/strong>)<\/h3>\n<p>Udo Steinbach wrote an e-mail to me about the issue with potentially throwing destructors. Here is the e-mail.<\/p>\n<p>RAII is a nice thing \u2212 as long as no error can occur while destroying the object. The latter is forgotten when talking about RAII. Why a destructor should not throw, you can read in many places: <a href=\"https:\/\/www.qwant.com\/?q=should%20destructors%20throw\">https:\/\/www.qwant.com\/?q=should%20destructors%20throw<\/a>. As a result, RAII has to be supplemented manually in many cases and so it seems to be done twice.<\/p>\n<p>&nbsp;<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0000ff;\">class<\/span> <span style=\"color: #2b91af;\">MyFileHandle<\/span>\r\n{  <span style=\"color: #0000ff;\">public<\/span>:\r\n      MyFileHandle(...)\r\n         :handle(::OpenFile(...))\r\n      {  <span style=\"color: #0000ff;\">if<\/span> (handle == nullptr)\r\n            <span style=\"color: #0000ff;\">throw<\/span> ...;\r\n      }\r\n      ~MyFileHandle() noexcept\r\n      {  ::CloseFile(handle);\r\n      }\r\n   private:\r\n      MySystemHandle handle;\r\n};\r\n\r\n\r\n{\r\n   MyFileHandle file(...);\r\n   ...\r\n}<br \/><br \/><\/pre>\n<\/div>\n<p>Does CloseFile() not close, the call looks correct but the handle is lost, the user has to restart the program and search and delete the file himself, or other embarrassing symptoms as they are familiar from programs.<\/p>\n<p>So the class must have a throwing<\/p>\n<pre><span style=\"font-family: courier new,courier;\">void Close();<\/span><\/pre>\n<p>and the destructor has to check:<\/p>\n<pre><span style=\"font-family: courier new,courier;\">{ <br \/>  MyFileHandle file(...)<br \/>  <\/span>... <br \/>  file.Close();<br \/>}<\/pre>\n<p>This doesn&#8217;t look like pure RAII. For symmetry we need a manual Open():<\/p>\n<pre>{<br \/>  MyFileHandle file;<br \/>  file.Open(...); <br \/>  ...<br \/><span id=\"transmark\"><\/span>  file.Close();<br \/>}<\/pre>\n<p>&nbsp;<\/p>\n<p>\u2212 RAII is lost. For the lover remains the consolation, that the object is now reusable and runs correctly in both non-error and error cases.<\/p>\n<p>Under the condition of proper error handling from the perspective of the program user, I renounce RAII in many of my classes. Automatic tests according to an idea from <a href=\"http:\/\/www.boost.org\/community\/exception_safety.html\">boost<\/a> show<\/p>\n<ul>\n<li>\n<p><a href=\"http:\/\/en.wikipedia.org\/wiki\/Exception_safety\">exception safety <\/a>as a minimum,<\/p>\n<\/li>\n<li>\n<p>with best-known error handling, which must be dispensed with at RAII, e.g. automatically delete incomplete files and rethrow the exception,<\/p>\n<\/li>\n<li>and messages presentable to the user,<\/li>\n<\/ul>\n<p>an always best possible behavior of the program: Make users and support happy by replacing crash and data garbage with meaningful messages. An automatism, here destructor or garbage collector, can handle errors only automatically: on a minimalistic scale or ignore it completely.<\/p>\n<p>In application programs this should not be accepted nor should it be.<\/p>\n<h2>The famous last words (Bjarne Stroustrup)<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-4962\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/09\/BjarneStroustrup.jpg\" alt=\"BjarneStroustrup\" width=\"400\" height=\"291\" style=\"margin: 15px;\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>Bjarne Stroustrup made a short remark to my news about this post on <a href=\"https:\/\/www.facebook.com\/groups\/cppEnthusiasts\/\">C++Enthusiasts: <\/a><\/p>\n<p><em>&#8220;Things are still improving&#8221;: <a href=\"http:\/\/www.stroustrup.com\/resource-model.pdf\">http:\/\/www.stroustrup.com\/resource-model.pdf<\/a><\/em><\/p>\n<p>&nbsp;<\/p>\n<p>So what is this 20 pages paper about, written by Bjarne Stroustrup, Herb Sutter, and Gabriel Dos Reis. I provide you with a screenshot of the abstract and the overview. You have to read the very readable paper by yourself.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5102\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/paper.png\" alt=\"paper\" width=\"700\" height=\"587\" style=\"margin: 15px;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/paper.png 989w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/paper-300x252.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2016\/12\/paper-768x645.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>I promise I will write in future posts about the Core C++ Guidelines. But you have to be patient. I first have to catch up with my German blog.<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>With the <a href=\"https:\/\/www.modernescpp.com\/index.php\/explicit-memory-management\">next post<\/a>, I enter the area of C++ experts. I write about explicit memory management in C++.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ is old-fashioned. C++ has no garbage collection. No garbage collection? Right! Old fashioned? Wrong!<\/p>\n","protected":false},"author":21,"featured_media":5101,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[364],"tags":[498],"class_list":["post-5103","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-embedded","tag-memory"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5103","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=5103"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5103\/revisions"}],"predecessor-version":[{"id":6907,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5103\/revisions\/6907"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5101"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5103"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5103"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5103"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}