{"id":30,"date":"2017-05-21T15:11:29","date_gmt":"2017-05-21T22:11:29","guid":{"rendered":"http:\/\/codingrestart.com\/?p=30"},"modified":"2017-05-21T15:11:29","modified_gmt":"2017-05-21T22:11:29","slug":"why-is-smart-pointer-better","status":"publish","type":"post","link":"https:\/\/codingrestart.com\/home\/why-is-smart-pointer-better\/","title":{"rendered":"Why is smart pointer better than a raw one?"},"content":{"rendered":"<p>In a previous <a href=\"http:\/\/codingrestart.com\/when-is-c-pointer-valid\/\">post<\/a>\u00a0I suggested that raw pointers should be replaced by smart pointers. This post explains why smart pointers are better than raw ones and how to convert an existing code using raw pointers to use smart pointers. For the sake of this post, when I refer to smart pointers, I talk about unique pointers, unique_ptr.<\/p>\n<h4>Why is smart pointer better?<\/h4>\n<p>Smart pointers have one crucial advantage over raw pointers: they guarantee that their destructors are called during stack unwinding. That means that any memory allocated in constructors will be automatically freed.<\/p>\n<p>Let&#8217;s look at sample code, that illustrates the advantage of smart pointers over raw pointers. First, let&#8217;s define a simple class that owns some memory, say std::string to store text.<\/p>\n<p><code>class Test<br \/>\n{<br \/>\n&nbsp;string s;<br \/>\npublic:<br \/>\n&nbsp;Test(string sVariable) :<br \/>\n&nbsp;&nbsp;s(sVariable)<br \/>\n&nbsp;{<br \/>\n&nbsp;&nbsp;cout &lt;&lt; \"Constructor (\" &lt;&lt; s &lt;&lt; \")...\" &lt;&lt; endl;<br \/>\n&nbsp;};<br \/>\n&nbsp;~Test()<br \/>\n&nbsp;{<br \/>\n&nbsp;&nbsp;cout &lt;&lt; \"Destructor (\" &lt;&lt; s &lt;&lt; \")...\" &lt;&lt; endl;<br \/>\n&nbsp;};<br \/>\n};<\/code><\/p>\n<p>Now assume that the main function will call myFunction() method to perform some operations. Main will catch any exceptions generated in myFunction() and exit the program.<\/p>\n<p><code>int main()<br \/>\n{<br \/>\n&nbsp;try<br \/>\n&nbsp;{<br \/>\n&nbsp;&nbsp;myFunction();<br \/>\n&nbsp;}<br \/>\n&nbsp;catch(...)<br \/>\n&nbsp;{<br \/>\n&nbsp;&nbsp;cout &lt;&lt; \"Exception handled\" &lt;&lt; endl;<br \/>\n&nbsp;}<br \/>\n&nbsp;<br \/>\n&nbsp;cout &lt;&lt; \"End\" &lt;&lt; endl;<br \/>\n&nbsp;return 0;<br \/>\n}<\/code><\/p>\n<p>Now let&#8217;s declare two pointers to Test class in myFunction(). First is rawPointer, which is raw pointer, and then smartPointer which is a smart pointer. Then let&#8217;s throw an exception to simulate some unexpected behavior of myFunction. At the end of the function we delete rawPointer. Note, that a smartPointer variable is not deleted as its destructor is guaranteed when the variable goes out of scope.<\/p>\n<p><code>int myFunction()<br \/>\n{<br \/>\n&nbsp;cout &lt;&lt; \"raw pointer\" &lt;&lt; endl;<br \/>\n&nbsp;Test *rawPointer = new Test(\"raw pointer\");<br \/>\n&nbsp;<br \/>\n&nbsp;cout &lt;&lt; \"smart pointer\" &lt;&lt; endl;<br \/>\n&nbsp;unique_ptr&lt;Test&gt; smartPointer = make_unique&lt;Test&gt;(\"smart pointer\");<br \/>\n&nbsp;<br \/>\n&nbsp;cout &lt;&lt; \"Throw!\" &lt;&lt; endl;<br \/>\n&nbsp;throw;<br \/>\n&nbsp;<br \/>\n&nbsp;cout &lt;&lt; \"Delete raw\u00a0pointer\" &lt;&lt; endl;<br \/>\n&nbsp;delete rawPointer;<br \/>\n&nbsp;<br \/>\n&nbsp;return 0;<br \/>\n}<\/code><\/p>\n<p>When we run this code, we see the following output:<\/p>\n<p><code>raw\u00a0pointer<br \/>\nConstructor (raw pointer)...<br \/>\nsmart pointer<br \/>\nConstructor (smart pointer)...<br \/>\nThrow!<br \/>\nDestructor (smart pointer)...<br \/>\nException handled<br \/>\nEnd<\/code><\/p>\n<p>Notice, that rawPointer variable is never deleted, causing a memory leak to occur.<\/p>\n<h3>How to convert raw pointers to smart pointers?<\/h3>\n<p>The above code provides a template how to convert existing code that is using raw pointers to smart pointers. To simplify the instructions, let&#8217;s use an example of code using raw pointers to int.<\/p>\n<ul>\n<li>Convert raw pointer declaration and allocation from<br \/>\n<code>int * rP;<br \/>\nrP = new int;<\/code><br \/>\nto<br \/>\n<code>unique_ptr&lt;int&gt; sP = make_unique&lt;int&gt;();<\/code><\/li>\n<li>Remove delete call to release rP memory<\/li>\n<\/ul>\n<p>That&#8217;s it! The code after the conversion is simpler and more robust, as you will never forget to delete the memory, or delete it twice, or the delete will simply be skipped by unexpected code flow (see the example using throw).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a previous post\u00a0I suggested that raw pointers should be replaced by smart pointers. This post explains why smart pointers are better than raw ones and how to convert an existing code using raw pointers to use smart pointers. For the sake of this post, when I refer to smart pointers, I talk about unique &hellip; <a href=\"https:\/\/codingrestart.com\/home\/why-is-smart-pointer-better\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Why is smart pointer better than a raw one?&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[2],"tags":[],"class_list":["post-30","post","type-post","status-publish","format-standard","hentry","category-cc"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/paAAlH-u","jetpack-related-posts":[{"id":11,"url":"https:\/\/codingrestart.com\/home\/when-is-c-pointer-valid\/","url_meta":{"origin":30,"position":0},"title":"When is C pointer valid?","author":"Viktor Sanek","date":"May 13, 2017","format":false,"excerpt":"C is largely based on raw pointers and one of the most often asked questions is when is a pointer a valid one. The reason is that dereferencing an invalid pointer generates an access violation exception (0xC0000005) and if not caught, the program crashes. You quickly learn there is IsBadReadPtr\u2026","rel":"","context":"In &quot;C\/C++&quot;","block_context":{"text":"C\/C++","link":"https:\/\/codingrestart.com\/home\/category\/uncategorized\/cc\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1,"url":"https:\/\/codingrestart.com\/home\/hello-programmers\/","url_meta":{"origin":30,"position":1},"title":"Hello programmers!","author":"Viktor Sanek","date":"May 7, 2017","format":false,"excerpt":"Welcome to CodingRestart.com, blog for seasoned developers that want to upgrade their skills. If any of the following is true for you, this site is for you: You feel threatened by younger colleagues, because you do not know popular programming languages and buzzwords they use. You think Kernighan and Ritchie's\u2026","rel":"","context":"Similar post","block_context":{"text":"Similar post","link":""},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":154,"url":"https:\/\/codingrestart.com\/home\/anki-introduction\/","url_meta":{"origin":30,"position":2},"title":"Anki: Introduction","author":"Viktor Sanek","date":"April 14, 2019","format":false,"excerpt":"This is the first article in a series of posts about Anki, a spaced learning system to improve users' long term memory. The next article in this series will cover the theoretical background of spaced learning, and the final article will concentrate on best practices using Anki. I have been\u2026","rel":"","context":"In &quot;Anki&quot;","block_context":{"text":"Anki","link":"https:\/\/codingrestart.com\/home\/category\/anki\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/04\/Starry1-1.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/04\/Starry1-1.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/04\/Starry1-1.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":171,"url":"https:\/\/codingrestart.com\/home\/theory-behind-anki\/","url_meta":{"origin":30,"position":3},"title":"Theory Behind Anki","author":"Viktor Sanek","date":"April 23, 2019","format":false,"excerpt":"This post covers the theory behind Anki and follows the previous post introducing Anki. The last post in this series describes best practices for using Anki. One of the best meta-analyses reviewing best approaches to learning is Improving Students\u2019 Learning With Effective Learning Techniques by Dunlosky et al. If I\u2026","rel":"","context":"In &quot;Anki&quot;","block_context":{"text":"Anki","link":"https:\/\/codingrestart.com\/home\/category\/anki\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":88,"url":"https:\/\/codingrestart.com\/home\/webassembly\/","url_meta":{"origin":30,"position":4},"title":"WebAssembly","author":"Viktor Sanek","date":"February 3, 2019","format":false,"excerpt":"Until recently, JavaScript was the only language supported by all web browsers. But it was difficult to compile it efficiently and the JavaScript applications typically run much slower than native applications. Then, programmers from the four main browser vendors designed a new language, sort of a machine code for the\u2026","rel":"","context":"In &quot;Web&quot;","block_context":{"text":"Web","link":"https:\/\/codingrestart.com\/home\/category\/web\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/01\/WASM.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/01\/WASM.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/01\/WASM.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/codingrestart.com\/wp-content\/uploads\/2019\/01\/WASM.png?resize=700%2C400&ssl=1 2x"},"classes":[]},{"id":139,"url":"https:\/\/codingrestart.com\/home\/mba-programs\/","url_meta":{"origin":30,"position":5},"title":"MBA Programs","author":"Viktor Sanek","date":"March 31, 2019","format":false,"excerpt":"A Master of Business administration (MBA) degree can be a valuable career enhancement for people that are already in, or think about switching to, management positions. MBA courses cover various areas of business such as accounting, finance, marketing, and operations. There are various types of MBA programs, including part-time, Executive\u2026","rel":"","context":"In &quot;Management&quot;","block_context":{"text":"Management","link":"https:\/\/codingrestart.com\/home\/category\/management\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/posts\/30","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/comments?post=30"}],"version-history":[{"count":12,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/posts\/30\/revisions"}],"predecessor-version":[{"id":43,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/posts\/30\/revisions\/43"}],"wp:attachment":[{"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/media?parent=30"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/categories?post=30"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codingrestart.com\/home\/wp-json\/wp\/v2\/tags?post=30"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}