<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pranay Kumar on Medium]]></title>
        <description><![CDATA[Stories by Pranay Kumar on Medium]]></description>
        <link>https://medium.com/@pranayaggarwal25?source=rss-8e13fd63c187------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lMFOuGw8woMQQW93XsVCNA.png</url>
            <title>Stories by Pranay Kumar on Medium</title>
            <link>https://medium.com/@pranayaggarwal25?source=rss-8e13fd63c187------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 10:23:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pranayaggarwal25/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Next higher palindrome using the same set of digits]]></title>
            <link>https://medium.com/geekculture/next-higher-palindrome-using-the-same-set-of-digits-2c8056e09755?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8056e09755</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 16:20:51 GMT</pubDate>
            <atom:updated>2021-06-13T08:55:45.281Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Problem:</strong> We are given a number N and we have to find the smallest possible palindrome greater than N that can be formed by using the same set of digits as in N. This problem is asked in many interviews and require an understanding step-by-step approach, also have applications in other manipulation problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*MBD1VfDFl8k2Gk1j.gif" /><figcaption>Let’s dive in!!</figcaption></figure><h3>Table of Contents</h3><ol><li>Background and example</li><li>Expectations from the optimal solution</li><li>Breaking down and visualizing the problem</li><li>Solution and approach</li><li>Source code</li></ol><h3>Background and Example</h3><p>What is a palindrome? A word, phrase, or sequence that reads the same backward as forwards, e.g. <strong><em>madam</em></strong> or 12321.</p><p><em>Let’s say we’re given the number 4697557964 which is a palindrome.</em></p><p><em>The next higher palindrome that can be formed using same digits is —</em></p><pre>4697557964 (Original number) </pre><pre>4756996574 Output</pre><h3>Expectations from the optimal solution</h3><ul><li>Time Complexity should be linear.</li><li>An auxiliary array may be used if needed.</li><li>As input numbers can be very large, take input as a string.</li></ul><h3>Breaking down and Visualizing the problem</h3><p>As palindrome means one half of the number is the mirror image of the other half like —</p><pre>46975 | 57964 </pre><pre>OR </pre><pre>47569 | 96574 </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*2B84Z7sb1yPzS4jNY0K24A.png" /><figcaption>Figure 1: Palindrome: A mirror image</figcaption></figure><p>Hence if we focus on one part only we are modifying —</p><pre><strong>46975</strong> (Input) =&gt; <strong>47569</strong> (Output we want)</pre><p>which is just the next higher number using the same set of digits. Thus the problem becomes —</p><h4>Problem 1: 📝</h4><p>For the first half, find the next higher number using the same set of digits</p><h4>Problem 2: 📝</h4><p>Mirror (Reverse) the first half to get second half and append.</p><h3>Solution and approach</h3><h4>Step1: Find a point of inversion (neighbor of local maxima)</h4><p>Why do you need to find a point of inversion from right to left OR basically a point which is smaller is than the right side?</p><blockquote>Point of inversion is the place that’s where the scope of improvement is in order to get higer number/sq</blockquote><p>Hence we find the inversion —</p><blockquote>Say complete part from right to left is increasing (or left to right is decreasing) like {9 7 5 4 3}, that means we can’t make a number bigger than this using these digits.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtxNVxq8poKNk-4ViPVnhQ.png" /><figcaption>Figure 2: Why Point of inversion?</figcaption></figure><p>Now let’s apply the same logic to our Input — <strong><em>46975</em></strong></p><p>Thus we find I = 6 as the inversion point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*Yh6jddBsRScAm-7GWAsYCg.png" /><figcaption>Figure3: Point of Inversion (I = 6)</figcaption></figure><p>If you notice here —</p><blockquote>Right side of Inversion Point(I) is sorted in decreasing order.</blockquote><p>As {4, 6, 9, 7, 5} =&gt; Right side of I = 6 is sorted i.e. 9,7,5.</p><h4>Step2: Find a suitable replacement</h4><p>Now we find which number (on the right of Inversion <strong>I</strong>) that can be used to replace this inversion, that’s how we’ll make a bigger number of course.</p><p>We should choose a replacement as small as possible out of all numbers bigger than I, to have the just next greatest number, not much.</p><blockquote>Finding smallest possible greater digit will lead to a larger number.</blockquote><pre>4 <strong>6</strong> 9 7 5<br>  |   <br>  I   S = ?</pre><p>If you check in figure 3, the minimum number bigger than <strong>I = 6</strong> is 7. Let’s call this 7 as S (Suitable Replacement)</p><p>How do you find S?</p><ul><li>Brute force — Iterate on the right side to find the minimum greater number (S) than Inversion (I).</li><li>Optimal Way — As the Right side is sorted, apply binary search to find S.</li></ul><blockquote><strong>Optimzation 1: </strong>As Right side of I is sorted, we can also apply binary search in order to find S.</blockquote><p>for e.g. we start on the right side of I, and we find 7 is the smallest replacement possible.</p><pre>4 <strong>6</strong> 9 <strong>7</strong> 5<br>  |   |<br>  I   S &lt;- found 7 min greater than 6</pre><h4>Step3: Swap and mirror</h4><p>As we have found a suitable replacement, we swap I and S, to get a greater number. We transform this —</p><pre>4 <strong>6</strong> 9 <strong>7</strong> 5<br>  |   |<br>  I   S </pre><pre>Swap I and S digits ==========&gt;</pre><pre>4 <strong>7</strong> 9 <strong>6</strong> 5<br>  |   |<br>  I   S</pre><p>We have achieved a bigger number now, Haven’t we? Yes. But is it the smallest possible greater number?</p><p>As now you see we already have a bigger number hence because we increased the number present at index I.</p><blockquote>After swap, there is no need for the number on right of I to be random, it should be smallest as possible. Hence we sort of the right of I.</blockquote><p>Hence</p><pre>4 7 9 6 5<br>  |   |<br>  I   S</pre><pre>Sort the part on the right side on I ==========&gt;</pre><pre><strong>4 7 5 6 9</strong></pre><p>becomes {4 7 5 6 9} which really is the smallest possible greater number than our Step1 input {4 6 9 7 5} using the same set of digits.</p><p>Hence our one part, Problem1 is solved now i.e.</p><h4><em>Problem 1 ✅</em></h4><p><em>For the first half, find the next higher number using the same set of digits</em></p><blockquote><strong>Optimzation 2: </strong>In Step 3 we already know it was sorted in decreasing manner except the element that we replaced it with. After that, right side of I would still be sorted in decreasing manner. Thus we directly reverse the right side of I instead of plain sort.</blockquote><p>Now to get the second half of the number, we mirror this and append it into itself</p><pre><strong>4 7 5 6 9 | &lt;Its reverse / mirror&gt;</strong></pre><pre>Mirror and append ==========&gt;</pre><pre><strong>4 7 5 6 9 | 9 6 5 7 4</strong></pre><p>Thus our Problem 2 is also solved now</p><h4>Problem 2 ✅</h4><p><em>Mirror (Reverse) the first half to get second half and append.</em></p><p>As we can verify our output, the next higher palindrome that can be formed using the same digits is —</p><pre>4697557964 (Original number)</pre><pre>4756996574 Output ✅</pre><p>Great, 😊 Isn’t it?</p><h3>Sample Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b35651d341375a66338f1bd86a1d24b2/href">https://medium.com/media/b35651d341375a66338f1bd86a1d24b2/href</a></iframe><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve this article.<br>Please check out my <a href="https://medium.com/pranayaggarwal25">other articles</a> and <a href="http://pranayaggarwal.github.io/">website</a>, Have a great day!</p><p>Please feel free to buy me a coffee <a href="https://www.buymeacoffee.com/pranayagrawal">here</a> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8056e09755" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/next-higher-palindrome-using-the-same-set-of-digits-2c8056e09755">Next higher palindrome using the same set of digits</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Domain Name System: A crash course on DNS for every developer]]></title>
            <link>https://pranayaggarwal25.medium.com/the-domain-name-system-for-every-developer-52568a2695be?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/52568a2695be</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[course]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[domain-names]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 16:00:34 GMT</pubDate>
            <atom:updated>2021-06-14T12:48:56.769Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is DNS? A crash course on DNS for every developer</h3><p>Did you ever think who understands <a href="https://google.com/">google.com</a> when you type that in your address bar? 🤔</p><p>How does this magic happen? ✨ There isn’t a delivery boy to hand over an HTML page directly. Let’s understand the crux of this superfast procedure 🚀 starting from typing a URL address to getting a page in your browser. <a href="https://emojipedia.org/laptop/">💻</a></p><p>If you ever need to set up a blog/website, this is a must-know article that contains all the understanding of DNS, the lookup process, types of DNS records i.e. all you need to know explained within a <strong>single</strong> article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*EPlbSCjMq1Ja7_6J" /><figcaption>DNS: Internet’s own complex library</figcaption></figure><h3>Table of Contents</h3><p>Here’s the outline of this article</p><ol><li>What is DNS?</li><li>Why is it required?</li><li>Types of DNS servers</li><li>How DNS resolution takes place via DNS servers?</li><li>Types of DNS Query</li><li>What is DNS caching? Where is it cached?</li><li>DNS Record Types and Bonus cheatsheet</li><li>Issues and Concerns</li></ol><h3>What is DNS?</h3><p>DNS stands out for “<strong>Domain Name System” </strong>which<strong> </strong>translates human-readable domain names (for example, www.amazon.com) to machine-readable IP addresses (for example, 192.0.2.44). DNS system is a public, hierarchical, distributed, and heavily cached database.</p><blockquote>DNS is like the Internet’s own phonebook. Records are searched in order to identify the IP address associated with a particular name</blockquote><p>An <strong>IP address</strong> is that unique <strong>address </strong>by which that server gets identified device on the internet (or on a local network). Once our computer/device has the IP address then we actually connect to the concerned website’s server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSNP08gBc6O2-LnBjz3Bfw.png" /><figcaption><strong>Figure 1: DNS server</strong></figcaption></figure><p>Thus DNS resolution of a website’s address involves a lookup process which is the DNS lookup.</p><h3>Why it is required?</h3><p>The domain name system (DNS) does the job of enabling a connection, for example to a website, without users having to know the corresponding IP.</p><p>Simple isn’t it? 😊</p><h3>Types of DNS Servers</h3><h4>1. Root Name Server</h4><p>DNS root nameservers are known to every recursive resolver based on the extension of that domain (.com, .net, .org, etc.) and a request is further assigned to a particular TLD responsible for such extension.</p><blockquote>The root nameservers are overseen by a nonprofit called the Internet Corporation for Assigned Names and Numbers (<strong>ICANN</strong>).</blockquote><h4>2. TLD Name Server</h4><p>A TLD nameserver maintains information for all the domain names that share a common domain extension, such as .com, .net</p><blockquote>Management of TLD nameservers is handled by the Internet Assigned Numbers Authority (<strong>IANA</strong>), which is a branch of ICANN.</blockquote><p>The IANA breaks up the TLD servers into two main groups:</p><ul><li><strong>Generic top-level domains —</strong> domains that are not country-specific such as .com, .org, .net, .edu, and .gov.</li><li><strong>Country code top-level domains — </strong>any domains that are specific to a country or state such as.uk, .us, .ru, and .jp.</li></ul><h4>3. Authoritative Name Server</h4><p>When a recursive resolver receives a response from a TLD nameserver, that response will direct the resolver to an authoritative nameserver. The authoritative nameserver is usually the resolver’s last step in the journey for an IP address.</p><h3>How DNS resolution takes place via DNS servers ⚙️ ?</h3><p><strong>Step 1: </strong>When you enter a URL into your browser, it starts searching for the corresponding IP-address in your computer’s DNS cache. If it finds no information there, the request will be redirected until the IP address will be identified.</p><p><strong>Step 2: </strong>Then it passes the local DNS-Server (usually your internet router), the ISP(Internet service provider) DNS-Server, and the root name server, which is accountable for the respective Top Level Domain (TLD).</p><p><strong>Step 3:</strong> If there is still no information found, the request will be sent to the Network Information Center (NIC) responsible for the zone. In the case of the TLD “.com”, this is Verisign.</p><p><strong>Step 4: </strong>The NIC’s server will send the address of the zone’s authoritative nameserver to the ISP. The ISP will then ask this authoritative server for the IP, and send the information through your router back to your browser. That way the website can be accessed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbOZIL34bKbaeaEeKijCLA.png" /><figcaption>Figure 2: <strong>DNS Query Resolution</strong></figcaption></figure><h3>Types of DNS Query</h3><ul><li>Recursive</li><li>Iterative</li></ul><p>A typical uncached DNS lookup will involve both recursive and iterative queries. Here, in figure 2—</p><ol><li>Query no. 2 to 7 are iteratively performed by the from ISP-Local DNS a.k.a recursive resolver.</li><li>DNS query after 1 is recursively performed by the recursive resolver (from the browser point of view)</li></ol><blockquote>A typical uncached DNS lookup will involve both recursive and iterative queries.</blockquote><h3>What is DNS caching? Where is it cached?</h3><p>The purpose of caching is to serve the last stored record for improvements in <strong>performance</strong> and <strong>reliability</strong> for future requests.</p><p>DNS caching involves storing data closer to the requesting client so that the DNS query can be resolved earlier and additional queries further down the DNS lookup chain can be avoided, thereby improving load times and reducing bandwidth/CPU consumption. DNS data can be cached in a variety of locations, each of which will store DNS records for a set amount of time determined by a time-to-live (TTL).</p><blockquote>At each level, caching takes place for the fetched records using TTL and other possible cache refreshment algorithms.</blockquote><h4>1. Browser level</h4><p>Moderns web browsers can do that. For e.g. you can check in chrome at -</p><pre>chrome://net-internals/#dns</pre><h4>2. Operating System Level</h4><p>The operating system level DNS resolver is the second and last local stop before a DNS query leaves your machine. The process inside your operating system that is designed to handle this query is commonly called a “stub resolver” or DNS client.</p><h3>DNS Record Types</h3><p>When you register a domain, you can set many types of DNS records. Each record has a Type, a Host, and a Value —</p><ul><li>“<strong>Types</strong>” are predefined</li><li>“<strong>Host</strong>” represents the root (@) or a subdomain (www)</li><li>“<strong>Value</strong>” is an IP or web address, or some other value.</li></ul><ol><li><strong>Address Mapping record (A Record) — </strong>maps a hostname to the corresponding IPv4 address.</li><li><strong>IP Version 6 Address record (AAAA Record) — </strong>maps a hostname to the corresponding IPv6 address.</li><li><strong>Canonical Name record (CNAME Record) — </strong>alias a hostname to another hostname. If a record that contains a CNAME points to another hostname, the DNS resolution is repeated with the new hostname.<br>Once you define a CNAME record for a subdomain (host), you CAN&#39;T DEFINE another record for that same subdomain. Because of this, you can’t use CNAME at the root level (where you need other records to exist)</li><li><strong>Alias Name Record (ANAME Record) — </strong>An ANAME record is like a CNAME record but at the root of your domain. That means you can point the “naked” version of your domain (like example.com ) to a hostname (like mycdn.com). <br><em>This is like a virtual CNAME and a </em><strong><em>non-standard DNS record.</em></strong></li><li><strong>Mail eXchanger record (MX Record) —</strong> specifies an SMTP email server for the domain.</li><li><strong>Name Server records (NS Record) —</strong> specifies that a DNS Zone, such as “hello.com” is delegated to a specific Authoritative Name Server, and provides the address of the name server.</li><li><strong>Reverse-lookup Pointer records (PTR Record) — </strong>allows a DNS resolver to provide an IP address and receive a hostname (reverse DNS lookup).</li><li><strong>Certificate record (CERT Record) —</strong> stores encryption certificates such as PKIX, SPKI, PGP, and so on.</li><li><strong>Service Location (SRV Record) — </strong>a service location record, like MX but for other communication protocols.</li><li><strong>Text Record (TXT Record) — </strong>typically carries machine-readable data such as opportunistic encryption, sender policy framework, etc.</li><li><strong>Start of Authority (SOA Record) —</strong> this record appears at the beginning of a DNS zone file, and indicates the Authoritative Name Server for the current DNS zone, contact details for the domain administrator, domain serial number, etc.</li></ol><h3>Bonus cheatsheet 🎉</h3><p>Here is a bonus cheat sheet for remembering all the important records —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsgHQALk21bxbCPQKXY44g.png" /><figcaption>Figure 3: A cheat sheet for important DNS records</figcaption></figure><h3>Issues and Concerns 🐛</h3><p>DNS cache poisoning is the act of entering false information into a DNS cache so that DNS queries return an incorrect response and users are directed to the wrong websites. DNS cache poisoning is also known as ‘DNS spoofing.’</p><p>IP addresses are the ‘room numbers’ of the Internet, enabling web traffic to arrive in the right places. DNS resolver caches are the ‘campus directory,’ and when they store faulty information, traffic goes to the wrong places until the cached information is corrected.</p><p>Because there is typically no way for DNS resolvers to verify the data in their caches, incorrect DNS information remains in the cache until the <strong>TTL</strong> expires, or until it is removed manually.</p><p>A more secure DNS protocol called <a href="https://en.wikipedia.org/wiki/Domain_Name_System_Security_Extensions">DNSSEC</a> aims to solve some of these problems, but it has not been widely adopted yet.</p><h3>References</h3><ol><li><a href="https://www.cloudflare.com/learning/dns/what-is-dns/">Cloudflare — what is DNS</a></li><li><a href="https://www.seobility.net/en/wiki/DNS_Server">Seobility — DNS records and types</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and share your feedback. Please feel free to drop any comments to improve this article.<br>Have a great day!😇</p><p>Please feel free to buy me a coffee ☕ =&gt; <a href="https://www.buymeacoffee.com/pranayagrawal">HERE</a> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52568a2695be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing smart pointers in C++]]></title>
            <link>https://levelup.gitconnected.com/passing-smart-pointers-in-c-479775632443?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/479775632443</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 16:39:18 GMT</pubDate>
            <atom:updated>2021-06-14T12:49:37.932Z</atom:updated>
            <content:encoded><![CDATA[<p>Dealing with smart pointers is a daily task for any C++ programmer and how to pass them around can get tricky when you are looking to achieve optimal performance. Here are some tips and general guidelines to follow for passing shared_ptr and unique_ptr as function arguments and at the time of return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MKKxnMeiF8CTX0zm" /></figure><blockquote>As always, prefer unique_ptr to shared_ptr, unless you intend to share ownership.</blockquote><h3>Introduction</h3><ol><li>Always ask yourself “Do I really need to pass a smart pointer ?”</li><li>std::unique_ptr usage</li><li>std::shared_ptr usage</li><li>How to pass correctly pass raw pointer/reference?</li><li>For Returning smart pointers, what is the norm?</li></ol><h3>Always ask yourself “Do I really need to pass a smart pointer ?”</h3><p>You should always assess if passing smart pointers as a function parameter is what you really need. In most cases, you just need to use it and be done with it. In those cases, it’s always good to get a raw pointer and pass it on.</p><p>Now before we go further, I must tell you that <strong>raw pointers aren’t always bad</strong>. They can be quite useful in many cases as we’ll read in this post.</p><h4>Guideline</h4><blockquote>Don’t pass a smart pointer as a function parameter unless you want to use or manipulate it, such as to share or transfer ownership.</blockquote><blockquote><strong>Prefer </strong>passing objects by non-owning raw pointers (<strong>*</strong>) OR references (<strong>&amp;</strong>).</blockquote><h4>Reason and Example</h4><pre>void f( widget* );              <br>void f( widget&amp; );</pre><p>They stay agnostic of whatever lifetime policy the caller use and are good to observe an object whose lifetime we know exceeds that of the pointer or reference.</p><p>This is restrictive and can’t be easy to commit always then we’ll see and assess the best possible way to pass smart pointers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CiD2BpQ9eDI1PX9OYMMLAQ.png" /><figcaption><strong>Step1: Know your lifetimes</strong> … The full picture would keep becoming more clear :)</figcaption></figure><p>So following should be the guideline if we are sure about the lifetime —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuRoK1HFOMg2xkZcSGyTIw.png" /><figcaption><strong>Guideline to follow in case of no share or transfer of ownership and valid lifetime</strong></figcaption></figure><h3>std::unique_ptr usage</h3><h4>By value unique_ptr&lt;type&gt; assumes ownership of a widget</h4><p><strong>Reason: </strong>This is the preferred way to express a consuming function, also known as a <strong>“sink”</strong>.</p><p>Using unique_ptr in this way in both documents and code, enforces well the function call’s ownership transfer (<em>Expresses a “sink” function)</em></p><p>Such as —</p><pre>void sink(unique_ptr&lt;widget&gt;); // takes ownership of the widget</pre><pre>// whereas</pre><pre>void uses(widget*);            // just uses the pointed object</pre><p>And a bad example is below —</p><pre>void thinko(const unique_ptr&lt;widget&gt;&amp;); // usually not what you want</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsARhJ6S3gqAHfiNkdIlGQ.png" /><figcaption><strong>unique_ptr passing guidelines</strong></figcaption></figure><p>and our guideline picture is now —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cp9haQg73JXSEN-xfrJB-g.png" /><figcaption><strong>Step2: Know your transfers</strong> … More clear picture :)</figcaption></figure><h4>Guideline:</h4><blockquote>Express a “sink” function using a by-value <strong>unique_ptr</strong> parameter. <em>Use a non-const </em><strong><em>unique_ptr&amp;</em></strong><em> parameter only to modify the </em><strong><em>unique_ptr</em></strong><em>.</em></blockquote><h3>std::shared_ptr usage</h3><h4>Passing shared_ptr by value only when you are sharing the ownership</h4><pre>void f( shared_ptr&lt;widget&gt; );  // only when you want to retain<br>                               // object and share ownership</pre><blockquote>Sharing ownership comes with a cost, so make sure you really mean and intend to pay that price.</blockquote><p>In pass by value, the argument is copied (usually unless temporary) on entry to the function, and then destroy (always) on function exit.</p><p>Passing <em>shared_ptr</em> by value means — <br>1) A new <strong><em>shared_ptr</em></strong> will be <strong>copy constructed.</strong><br>2) Ref count which is an atomic shared variable gets increased.<br>3) <strong><em>shared_ptr</em></strong> copy gets destroyed at the end of the function.<br>4) Ref count which is an atomic shared variable gets decreased.</p><p>[ Related post: <a href="https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc">https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc</a> ]</p><pre>void f( const shared_ptr&amp;&lt;widget&gt; );   // may share ownership<br>void f( shared_ptr&amp;&lt;widget&gt; );         // may reset pointer</pre><p>In the special case where the function <em>might</em> share ownership but doesn’t necessarily take a copy of its parameter on a given call, then pass a const-ref to avoid the copy on the calls that don’t need it. So for <strong><em>shared_ptr</em></strong> follow this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VklHsi0KmZw17S5o0VW8Q.png" /><figcaption><strong>shared_ptr passing guidelines</strong></figcaption></figure><p>And finally, we have our full guideline picture here —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZhPV6_u-926_gDzo-_RHg.png" /><figcaption><strong>Step3: The final guideline picture</strong></figcaption></figure><h3>How to pass correctly pass raw pointer/reference?</h3><p>As we have seen above that functions should prefer to pass raw pointers and references down call chains wherever possible.</p><p>At the top of the call tree where you obtain the raw pointer or reference from a smart pointer that keeps the object alive. You need to be sure that the smart pointer cannot inadvertently be reset or reassigned from within the call tree below.</p><p><strong>To do this, sometimes you need to take a local copy of a smart pointer, which firmly keeps the object alive for the duration of the function and the call tree.</strong></p><p>Consider this code, the following should not pass code review:</p><pre>// global (static or heap), or aliased local ...<br>shared_ptr&lt;widget&gt; g_p = ...;</pre><pre>void my_code()<br>{<br>    // <strong>BAD:</strong> passing pointer or reference obtained from a non-local<br>    // smart pointer that could be inadvertently reset somewhere <br>    // inside f or its callees<br>    f(*g_p);</pre><pre>// <strong>BAD:</strong> same reason, just passing it as a &quot;this&quot; pointer<br>    g_p-&gt;func();<br>}</pre><p>The fix is simple — take a local copy of the pointer to keep a ref count for your call tree:</p><pre>// global (static or heap), or aliased local ...<br>shared_ptr&lt;widget&gt; g_p = ...;</pre><pre>void my_code()<br>{<br>    // <strong>cheap:</strong> 1 increment covers this entire function and call trees <br>    auto pin = g_p;</pre><pre>// <strong>GOOD:</strong> passing pointer or reference obtained from a local <br>    // unaliased smart pointer<br>    f(*pin);</pre><pre>// <strong>GOOD:</strong> same reason<br>    pin-&gt;func();<br>}</pre><h3>For Returning smart pointers, what is the norm?</h3><p>You should follow the same logic above:</p><blockquote>Return smart pointers if the caller wants to manipulate the smart pointer itself, return raw pointers/references if the caller just needs a handle to the underlying object.</blockquote><p>If you really need to return smart pointers from a function, take it easy and always return <em>by value</em>. That is:</p><pre>std::unique_ptr&lt;Object&gt; getUnique();<br>std::shared_ptr&lt;Object&gt; getShared();<br>std::weak_ptr&lt;Object&gt;   getWeak();</pre><p>There are at least three good reasons for this:</p><ol><li><strong>Move Semantics</strong> <strong>— </strong>Smart pointers are powered by move semantics: the dynamically-allocated resource they hold is moved around, not wastefully copied.</li><li><strong>Return Value Optimization (RVO)</strong> <strong>— </strong>All modern compilers are able to detect that you are returning an object by value, and they apply a sort of return shortcut to avoid useless copies. Starting from C++17, this is guaranteed by the standard. Returning by reference inhibits that shortcut.</li><li><strong>Object deletion probability — </strong>Returning std::shared_ptr by reference doesn&#39;t properly increment the reference count, which opens up the risk of deleting something at the wrong time, by incurring the risk of having the object deleted (that may be local) when it goes out of scope in another context.</li></ol><p>Thanks to RVO. you don’t need to move anything when returning a std::unique_ptr also.</p><pre>std::unique_ptr&lt;Object&gt; getUnique()<br>{<br>    std::unique_ptr&lt;Object&gt; p = std::make_unique&lt;Object&gt;();<br>    return p; <br>    // also return std::make_unique&lt;Object&gt;();<br>}</pre><h3>References</h3><ol><li><a href="https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/">https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/</a></li><li><a href="http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-uniqueptrparam">http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-uniqueptrparam</a></li><li><a href="https://www.internalpointers.com/post/move-smart-pointers-and-out-functions-modern-c">https://www.internalpointers.com/post/move-smart-pointers-and-out-functions-modern-c</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and share what you think. Please feel free to drop any comments to improve this article.<br>Have a great day!</p><p>Please feel free to buy me a coffee ☕ =&gt; <a href="https://www.buymeacoffee.com/pranayagrawal">HERE</a> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=479775632443" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/passing-smart-pointers-in-c-479775632443">Passing smart pointers in C++</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambdas and closures in C++]]></title>
            <link>https://pranayaggarwal25.medium.com/lambdas-closures-c-d5f16211de9a?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f16211de9a</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 06:04:23 GMT</pubDate>
            <atom:updated>2021-06-14T12:49:54.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lambdas and Closures in C++</h3><p>A lambda function is a function that you can write inline in your source code In this article, I’ll first explain why lambdas are great, what are closures vs how lambdas are different from closures? — with some examples — and then I’ll walk through all of the details of what you can do with lambda.</p><p>What are closures vs how lambdas are different from closures?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*PA8-5rLUUze-e0iK" /><figcaption>They look similar!!</figcaption></figure><h3>Table of Contents</h3><ol><li>Just your everyday functions</li><li>Lambda Expressions</li><li>What are closures</li><li>Lambdas vs. Closures</li><li>Distinction by Examples</li><li>Close analog to a closure</li></ol><h3>Just your everyday functions</h3><p>When most people think of <em>functions</em>, they think of <strong>named functions </strong>such as -</p><pre>std::string a_named_function () { <br>    return &quot;This string is returned from a named function&quot;; <br>}</pre><pre><strong>// A named function</strong></pre><p>These are called by name, of course:</p><pre>foo(); //returns the string above</pre><h3>Lambda Expressions</h3><p>The term “lambda” is short for <em>lambda expression</em>, and a lambda is just that 😊:</p><p>1. <strong>Lamdba expression </strong>— An <em>expression </em>that specifies an anonymous function object, just syntax for creating an unnamed function.</p><p>2. <strong>Lamdba function — </strong>This term is used interchangeably with the term “lambda expression.”</p><p>As such, it exists only in a program’s source code.</p><blockquote>A lambda does not exist at runtime.</blockquote><p>A lambda expression <strong>specifies an object</strong>, <strong>not just a function without a name, </strong>capable of capturing variables in scope.</p><ul><li>Lambdas can frequently be passed around as objects.</li><li>A lambda is essentially a function object that is specified inline.</li><li>In addition to its own function parameters, a lambda expression can refer to local variables in the scope of its definition.</li></ul><h3>What are closures</h3><blockquote>Closures are special functions that can capture the environment, i.e. variables within a <strong>lexical scope</strong>.</blockquote><p><em>A </em><strong><em>closure</em></strong><em> is any function that </em><strong><em>closes over</em></strong><em> the </em><strong><em>environment</em></strong><em> in which it was defined. This means that it can access variables, not in its parameter list.</em></p><h4>* What is C++ specific part here</h4><p><em>A closure is a general concept in programming that originated from functional programming. When we talk about the closures in C++, they always come with lambda expressions (some scholars prefer the inclusion of function object in this)</em></p><ol><li>In c++ a lambda expression is the syntax used to create a special temporary object that behaves similarly to how function objects behave.</li><li>The C++ standard specifically refers to this type of object as a <em>closure object</em>. This is a little bit at odds with the broader definition of a closure, which refers to any function, anonymous or not, that captures variables from the environment they are defined in.</li><li>As far as the standard is concerned, all instantiations of lambda expressions are closure objects, even if they don’t have any captures in their capture group.</li></ol><p><em>In any other language like Python, closure is unrelated to Lambdas </em>😊</p><h4>What is a Closure anyway in C++?</h4><p>A value* defined (rather encapsulated) by lambda expression that consists of both the code as well as the values of the variables referred to in the code.<br>(We will discuss this asterisk * further in this article)</p><p>So closure is an anonymous function object that is created automatically by the compiler as the result of a lambda expression. A closure stores those variables from the scope of the definition of the lambda expression that is used in the lambda expression.</p><blockquote>The runtime effect of a lambda expression is the generation of an object. Such objects are known as <em>closures</em>.</blockquote><p>A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure</p><h3>Lambdas vs. Closures for C++</h3><p><strong>Scott Meyers</strong> puts it beautifully — “<strong>The distinction between a lambda and the corresponding closure is precisely equivalent to the distinction between a class and an instance of the class</strong>”.</p><blockquote>Closures are to lambdas as objects are to classes.</blockquote><p>As we know, a class exists only in source code; it doesn’t exist at runtime. What exists at runtime are objects of the class type. Similarily -</p><blockquote>Each lambda expression causes a unique class to be generated (during compilation) and also causes an object of that class type–a closure–to be created (at runtime).</blockquote><ol><li>Lambdas occupy no data memory at runtime, for example, though they may occupy code memory.</li><li>Closures occupy data memory, but not code memory.</li></ol><h3>Distinction by Examples</h3><p>Let’s take an example —</p><pre><strong>auto f =</strong> [&amp;](int x, int y) { return fudgeFactor * (x + y); };</pre><pre>// the expression to the right of the &quot;=&quot; is the lambda expression (i.e., &quot;the lambda&quot;),</pre><pre><strong>// The runtime object created by that expression is the closure.</strong></pre><p>f itself is not a closure, it is a <strong><em>copy of the closure </em>🥴</strong></p><h4>Ok, what do you mean?</h4><p>The process of copying the closure into f may be optimized into a move but that doesn&#39;t change the fact that f itself is not the closure.</p><p>The actual closure object is a temporary that’s typically destroyed at the end of the statement unless you bind it to a <a href="https://medium.com/pranayaggarwal25/universal-reference-perfect-forwarding-5664514cacf9">forwarding reference(a.ka. Universal reference)</a> or lvalue-reference-to-const.</p><pre>//===============================================================//</pre><pre>auto&amp;&amp; <strong>rrefToClosure</strong> = [&amp;](int x, int y) { return fudgeFactor * (x + y); };</pre><pre>const auto&amp; <strong>lrefToConstToClosure</strong> = [&amp;](int x, int y) { return fudgeFactor * (x + y); };</pre><pre>//===============================================================//</pre><p>Let’s take another example —</p><pre>//===============================================================//</pre><pre>std<strong>::</strong>function<strong>&lt;void</strong>(<strong>void</strong>)<strong>&gt;</strong> closureWrapper1()<br>{<br>    <strong>int</strong> x <strong>=</strong> 10;<br>    <strong>return</strong> [&amp;x](){ std<strong>::</strong>cout <strong>&lt;&lt;</strong> &quot;Value in the closure: &quot; <strong>&lt;&lt;</strong> x++ <strong>&lt;&lt;</strong> std<strong>::</strong>endl; };<br>}</pre><pre><strong>int</strong> <strong>main</strong>()<br>{<br>    <strong>int</strong> x <strong>=</strong> 10;<br>    <strong>auto</strong> func0 <strong>=</strong> [<strong>&amp;</strong>x](){x <strong>+=</strong> 1; std<strong>::</strong>cout <strong>&lt;&lt;</strong> &quot;Value in the closure: &quot; <strong>&lt;&lt;</strong> x <strong>&lt;&lt;</strong> std<strong>::</strong>endl;};<br>    <br>    func0();  // Prints 11</pre><pre>std<strong>::</strong>function<strong>&lt;void</strong>(<strong>void</strong>)<strong>&gt;</strong> func1 <strong>=</strong> closureWrapper1();</pre><pre>func1();  // Prints garbage value + 1 =~ garbage value</pre><pre>}</pre><pre>//===============================================================//</pre><p>func1 is not closure Instead, it’s astd::function wrapper object that wrapped a closure.</p><p>func0 is a copy of a closure created by the lambda expression written after it.</p><h3>Close analog to a closure</h3><p><strong>Function Object (Functor)</strong> — Function object overload the operator(). It could capture the values by making a copy of the variables to its member variables. The shortcoming is that for each different function call, regardless of how simple it is, we would have to implement a new class, whereas implementing a lambda expression is faster.</p><h3>References</h3><ol><li><a href="http://scottmeyers.blogspot.com/2013/05/lambdas-vs-closures.html">http://scottmeyers.blogspot.com/2013/05/lambdas-vs-closures.html</a></li><li><a href="https://leimao.github.io/blog/CPP-Closure/">https://leimao.github.io/blog/CPP-Closure/</a></li><li><a href="https://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda">https://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve this article.<br>Have a great day!</p><p>Please feel free to buy me a coffee ☕ =&gt; <a href="https://www.buymeacoffee.com/pranayagrawal">HERE</a> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f16211de9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object construction order in case of virtual and/or multiple inheritance]]></title>
            <link>https://medium.com/pranayaggarwal25/object-construction-in-case-of-virtual-multiple-inheritance-dcf8909f228b?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf8909f228b</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 19:07:17 GMT</pubDate>
            <atom:updated>2021-06-14T12:50:09.737Z</atom:updated>
            <content:encoded><![CDATA[<p>How virtual vs. multiple inheritance affect class object construction order?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*VtNlssb8zTqF0nY9.gif" /></figure><p>I’ll try to keep this post short and simple 😊</p><h3>Table of Contents</h3><ol><li>An example class having virtual and/or multiple inheritance</li><li>What are the rules for object construction order?</li><li>Understanding the object construction order rules</li><li>Let’s apply the rules, shall we?</li><li>Bonus Question</li></ol><h3>Example: A class having virtual and/or multiple inheritance</h3><p>class Xis declared here as inherited by D1, D2 which in turn are inherited by other class in a complex manner by other classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*9ZFGEBfTvwaafG1tsZR4QQ.png" /><figcaption>This will be our complex example</figcaption></figure><p>Here as we clearly see following can be established — <br>1) V1 inherited by B1<br>2) D1 inherited by V1<br>3) V2 inherited by B1 and B2<br>4) D2 inherited by B3 and V2<br>5) X inherited by D1 and D2</p><h3>What are the rules for object construction order?</h3><p>The following set of rules is applied recursively:-</p><h4>1. First comes virtual</h4><p>First, the most derived class’s constructor calls the constructors of the virtual base class subobjects. The very first constructors to be executed are the virtual base classes anywhere in the hierarchy. <br>Virtual base classes are initialized<strong> In depth-first, left-to-right order.</strong></p><h4>2. Then comes multiple inheritance —</h4><p>After all virtual base class constructors are finished, the construction order is generally from base class to derived class. Direct base class subobjects are constructed <strong>in the order they are declared in the class definition</strong>.</p><h4>3. Next comes class members</h4><p>Next, (nonstatic) member subobjects are constructed, in the order, they were declared in the class definition.</p><h4>4. Finally the constructor body</h4><p>In the last, the body of the constructor is executed.</p><p>Also, one point to be noted is that —</p><blockquote>Whether the inheritance is public, protected, or private doesn’t affect initialization order</blockquote><h3>Understanding the object construction order rules</h3><p>The rules are easiest to understand if you imagine that the very first thing the compiler does in the derived class’s constructor is to make a hidden call to the constructors of its virtual base and then non-virtual base classes (hint: that’s the way many compilers actually do it).</p><blockquote>It’s like a DFS where the order on a same level is driven by class definition</blockquote><p>Example — class <strong><em>D</em></strong> inherits from both <strong><em>B1</em></strong> and <strong><em>B2</em></strong>,</p><ol><li>The constructor for <strong><em>B1</em></strong> executes first</li><li>then the constructor for <strong><em>B2</em></strong>,</li><li>Then the constructor for <strong><em>D</em></strong>. <br>This rule is applied recursively</li></ol><p>For example, if <strong><em>B1</em></strong> inherits from <strong><em>B1a</em></strong> and <strong><em>B1b</em></strong>, and <strong><em>B2</em></strong> inherits from <strong><em>B2a</em></strong> and <strong><em>B2b</em></strong>, then the final order is <br>1. <strong><em>B1a</em></strong> =&gt; <strong><em>B1b</em></strong> =&gt; <strong><em>B1</em></strong>, and then <br>2. <strong><em>B2a =&gt; B2b =&gt;</em></strong> <strong><em>B2</em></strong><em> <br>3. </em>and ofcourse in the end<em> </em><strong><em>D</em></strong>.</p><p>Note that the order <strong><em>B1</em></strong> and then <strong><em>B2</em></strong> (or <strong><em>B1a</em></strong> then <strong><em>B1b</em></strong>) is determined by the order that the base classes appear in the declaration of the class, <em>not</em> in the order that the initializer appears in the derived class’s initialization list.</p><p>[ Refer <a href="https://medium.com/pranayaggarwal25/using-modern-class-members-and-initializations-c11e931c3ba">https://medium.com/pranayaggarwal25/using-modern-class-members-and-initializations-c11e931c3ba</a> for more details about class member initializations ]</p><h3>Let’s apply the rules, shall we?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*9ZFGEBfTvwaafG1tsZR4QQ.png" /><figcaption>Looks easier now, doesn’t it?</figcaption></figure><p>The initialization order for a X object in Example 2 is as follows, where each constructor call shown represents the execution of the body of that constructor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-qxlGwcVWru5zB3Xo_4Yw.png" /></figure><p>So —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*TTTVf62ztLB7o-Z0g3na2A.png" /><figcaption>First — Construct the virtual bases V1 and V2 recursively by rules</figcaption></figure><p>After that, construct the remaining nonvirtual bases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*TY1_6ucxEUqM8HNQgeMsgQ.png" /><figcaption>Second — Construct the remaining non-virtual bases D1 and D2</figcaption></figure><p>Next, construct the members <strong><em>M1</em></strong> and <strong><em>M2 —</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cDhZbtSxlmIfZanCtUjkAA.png" /><figcaption>Third — Class member construction</figcaption></figure><p>and in the last —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*d0jyqK1WZL9p4MfTVvnRlg.png" /><figcaption>Final construction</figcaption></figure><p>if you’re a fan of graphics, here is how the inheritance hierarchy looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*lNJNK6S_PTgulnoservZoQ.png" /><figcaption>Inheritance and object construction hierarchy (v means Virtual)</figcaption></figure><p>That’s pretty much it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*RymMjGO7qYGCJPV2" /></figure><h3>Bonus Question Time, yay!! 😉</h3><p>Thanks for reading it till here.</p><h3>What is the exact order of destructors in a multiple and/or virtual inheritance situation?</h3><p>The exact opposite of the same constructor order.</p><p>Reminder to make your base class’s destructor virtual, at least in the normal case. Why, I think you already know why? 😊</p><p>When someone says delete using a Base pointer that’s pointing at a Derived object, had Base’s destructor not been virtual, Derived’s destructor would not have been called – with likely bad effects, such as resources owned by Derived not being freed.</p><h3>References</h3><ol><li><a href="http://www.gotw.ca/gotw/080.htm">http://www.gotw.ca/gotw/080.htm</a></li><li><a href="https://isocpp.org/wiki/faq/multiple-inheritance#mi-vi-ctor-order">https://isocpp.org/wiki/faq/multiple-inheritance#mi-vi-ctor-order</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve this article.<br>Please check out my <a href="https://medium.com/pranayaggarwal25">other articles</a> and <a href="http://pranayaggarwal.github.io/">website</a>, Have a great day!</p><p>Please feel free to buy me a coffee ☕ =&gt; <a href="https://www.buymeacoffee.com/pranayagrawal">HERE</a> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf8909f228b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/object-construction-in-case-of-virtual-multiple-inheritance-dcf8909f228b">Object construction order in case of virtual and/or multiple inheritance</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Modern C++ class members and initializations the right way]]></title>
            <link>https://medium.com/pranayaggarwal25/using-modern-class-members-and-initializations-c11e931c3ba?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11e931c3ba</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 17:00:59 GMT</pubDate>
            <atom:updated>2021-06-14T12:50:43.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modern C++ class members and initializations the right way</h3><p>Using In-member initialization, using constructors smartly and using class members functions in a safe and proper way to avoid mistakes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*csRd0YjayeNTl96F.jpg" /><figcaption>Clean code!</figcaption></figure><h3>Table of Contents</h3><ol><li>Use member initializers in the same order as their declaration</li><li>Prefer in-class member initializer over constant initializations OR over default constructor.</li><li>Don’t cast away const, ever!</li><li>Use delegating constructors to represent common actions for all constructors of a class.</li></ol><h3>1. Use member initializers in the same order as their declaration</h3><p>Member variables are always initialized in the order they are declared in the class definition.</p><p><strong>The order in which you write them in the constructor initialization list is ignored 🥴</strong></p><p>Make sure the constructor code doesn’t confusingly specify different orders. For e.g. this case as below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Wzlu5I7J1KamJhQYob7_4w.png" /><figcaption>Would lead to issues</figcaption></figure><p>email is declared before first_name and last_name in the class definition, hence as per the constructor call, it will be initialized first and will attempt to use the other not-yet-initialized fields which are first_name and last_name .</p><h4>How to make it right</h4><p>This code harbors a bug that’s as subtly harmful as it is hard to spot hence</p><blockquote>Write member initializers in the same order as their declaration</blockquote><p>Many compilers (but not all) will issue a warning if you break this rule. Modern compilers Clang, MSVC detect it with the right use of right warning flags.</p><h4>Reason</h4><p>The reason for this language design decision is to ensure there is a unique order to destroy members; otherwise, the destructor would have to destroy objects in different orders, depending on the constructor that built the object.</p><h4>Benefit</h4><ol><li>Protects you from an oddity of the language without requiring everyone to know it.</li><li>Might encourage you to rethink your class design so this dependency goes away</li></ol><h3>2. Prefer in-class member initializer over constant initializations OR over default constructor</h3><p>You should don’t define a default constructor that only initializes data members; use in-class member initializers instead which works as a good fallback in case you forget to initialize something.</p><p>Example — A bad class that misses one initialization in a constructor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*iRhyfPkavdlODmNqmNEKsw.png" /><figcaption><strong>Cons of not using in-member class initializers</strong></figcaption></figure><p>where the following is an example of a much better class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*GNGSOMx_9NcelulDaYnytg.png" /><figcaption><strong>Using in-member class initializers, Nice!!</strong></figcaption></figure><h4>Reason</h4><p>Using in-class member initializers lets the compiler generate the function for you. Also, the compiler-generated function can be more efficient 😊</p><h4>Benefits</h4><ol><li>No overhead of taking care of initializing constants separately in each constructor.</li><li>Performance gain by using standard default constructors.</li></ol><h3>3. Don&#39;t cast away const, ever!</h3><p>We shouldn’t cast away from getter functions even when there seems a need.</p><p>For e.g. — Stuff is a class that does some calculations overnumber1 and number2 and computes the result. Now getValue() const is a function that fetches the value, and being a getter function is marked const.</p><p>number1 and number2 are updated byService1() and Service2() functions respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*AuUxrjVaYzHmo_OacXV5qA.png" /></figure><p>Now, in case read frequency of getValue() is much more than the number of writes, we should preemptively update the cachedValue which is returned.</p><p>Such as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*rqMbsx6k1igbaXt3OKW5dw.png" /></figure><p>However, in case the number of writes is much more, we should follow <strong>a lazy calculation approach</strong> where we set a dirty flag such as below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*TD_ZSa_Y2-jmsOZHZO8B2w.png" /><figcaption>getValue function would show error as it’s marked const</figcaption></figure><p>But this poses a problem because const function can not modify this <strong>newly introduced class member variable </strong>cachedValid .</p><ol><li><strong>A wrong fix </strong>would be to remove const from<strong> </strong>getValue() function</li><li><strong>Another wrong fix </strong>would be to const_cast over “<em>this”</em> pointer.</li></ol><h4>Reason</h4><p>Doing this makes a lie out of const. Any variable is actually declared asconst, modifying it may result in undefined behavior.</p><ol><li>Allows getValue() function to change anything in the instance.</li><li>The header file is now speaking a lie basically.</li></ol><h4>Correct Fix</h4><p>The right fix would be to declare cachedValid and cachedValue as mutable so that thegetValue() function can only modify the mutable ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*DgxaGoDSuAcpP58716AYRQ.png" /><figcaption>The correct fix</figcaption></figure><h4>Benefits of correct fix</h4><ul><li>Header file tells the truth</li><li>getValue() function can only change the mutable variables</li><li>Code accessing mutable members is shorter and more readable</li><li>Easier to write, read, and maintain</li><li>Const-correctness may enable optimizations 😊</li></ul><h3>4. Use delegating constructors to represent common actions for all constructors of a class</h3><p>The common action gets tedious to write and may accidentally not be common. Hence, wherever possible we should refer to existing constructors.</p><p>For e.g. — This Date is a bad class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*WNgLgmo1n2TEsdoGYPy_EQ.png" /><figcaption>A bad series of constructors, duplicate logic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*B5w6vP4oil0rnbYdMWkyng.png" /><figcaption><strong>Good!! Using delegating constructors</strong></figcaption></figure><h4>Reason</h4><p>To avoid repetition and accidental differences.</p><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=XkDEzfpdcSg">https://www.youtube.com/watch?v=XkDEzfpdcSg</a></li><li><a href="https://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586">C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter, Andrei Alexandrescu</a></li><li><a href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines">https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve this article.<br>Please check out my <a href="https://medium.com/pranayaggarwal25">other articles</a> and <a href="http://pranayaggarwal.github.io/">website</a>, Have a great day!</p><p>Please feel free to buy me a coffee ☕ =&gt; <a href="https://www.buymeacoffee.com/pranayagrawal">HERE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11e931c3ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/using-modern-class-members-and-initializations-c11e931c3ba">Using Modern C++ class members and initializations the right way</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Few Modern C++ Puzzles]]></title>
            <link>https://medium.com/pranayaggarwal25/modern-c-puzzles-fc13ed56f67a?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc13ed56f67a</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 15:44:27 GMT</pubDate>
            <atom:updated>2020-06-15T15:44:27.820Z</atom:updated>
            <content:encoded><![CDATA[<p>Some puzzles from various talks, blog posts, and other bits</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*3StcFi7Mii7eFJOZ.png" /></figure><h3>Table of Contents</h3><ol><li>Puzzle 1: Capturing unique_ptr by reference</li><li>Puzzle 2: Capturing the temporary by the reference</li><li>Puzzle 3: Making mistakes with std functions usage</li><li>Puzzle 4: Throwing away the dead</li></ol><h3>Puzzle 1: Capturing unique_ptr by reference</h3><pre>unique_ptr&lt;A&gt; myFun()<br>{<br>    unique_ptr&lt;A&gt; pa(new A());<br>    return pa;<br>}<br><br>const A&amp; rA = *myFun();</pre><p>This code compiles but rA contains garbage. Why is this code invalid?</p><p><strong>Note: </strong>if we assign the return of myFun to a named unique_ptr variable before dereferencing it, it works fine.</p><h4><strong>Answer:</strong></h4><p>The unique_ptr will pass the ownership to another unique_ptr, but in this code, there is nothing to capture the ownership from the returning pointer. In other words, It can not transfer the ownership, so it will be destructed. The proper way is:</p><pre>unique_ptr&lt;A&gt; rA = myFun(); // Pass the ownership</pre><p>or</p><pre>const A rA = *myFun(); // Store the values before destruction</pre><p>In this code, the returning pointer will be destructed and the reference is referring to an object which is destructing soon after that using this reference invokes undefined behavior.</p><h3>Puzzle 2: Capturing the temporary by the reference</h3><pre>vector&lt;bool&gt; vb{true, true, false, true};</pre><pre>auto proxy = vb[0];</pre><pre>std::cout &lt;&lt; proxy // <strong>ok, Prints true</strong></pre><pre>vb.reserve(100); // A: ???</pre><pre>std::cout &lt;&lt; proxy // <strong>Error!!</strong> likely to print false on clang, why?</pre><h4>Answer:</h4><p>Line A invalidates proxy so proxywas invalidated by vb.reserve.</p><p>Take below example —</p><pre>void example_1_1_3() {</pre><pre><br>string_view s;      // s points to null</pre><pre>string name = &quot;abcdefghijklmnop&quot;;</pre><pre>s = name;        // A: s points to {name&#39;} i.e. data owned by name’</pre><pre>cout &lt;&lt; s[0];    // B: ok – s[0] is ok because {a} is alive</pre><pre>name = &quot;frobozz&quot;;  // C: name modified =&gt; name’ is invalid</pre><pre>cout &lt;&lt; s[0];      // D: error – because it contains {invalid}</pre><pre>}</pre><p>which is why guideline says —</p><blockquote>Never use the reference in case of a temporary argument.</blockquote><p>Take below example —</p><pre>char&amp; c = std::string{&quot;hello my pretty long string&quot;}[0];</pre><pre>cout &lt;&lt; c; // <strong>(X) wrong</strong> to initialize a<br>// reference ‘c’ with an invalid pointer, pointer<br>// was invalidated with temporary string was<br>// destroyed.</pre><h3>Puzzle 3: Making mistakes with std functions usage</h3><pre>int main() {<br> <br> auto x=10, y=2;<br> auto&amp; good = min(x,y); // ok, {x,y}<br> <br> cout &lt;&lt; good; <strong>// ok, fine.</strong></pre><pre> auto&amp; bad = min(x,y+1) </pre><pre> cout &lt;&lt; bad; <strong>// ERROR, why??</strong><br>}</pre><h4>Answer:</h4><pre>int main() {<br> <br> auto x=10, y=2;<br> auto&amp; good = min(x,y); // ok, {x,y}<br> <br> cout &lt;&lt; good; <strong>// ok, fine.</strong></pre><pre>auto&amp; bad = min(x,y+1) <br> // A: IN: {x, temp(y+1)}<br> // OUT: temp2 obtained by {x,temp}</pre><pre>// min() returns temp2<br><br> // temp destroyed hence → temp2 = {invalid}</pre><pre>cout &lt;&lt; bad; <strong>// ERROR, bad initialized as invalid now</strong><br>}</pre><p>In normal C++, this code compiles but has <strong>undefined behavior</strong>.<br>Note In practice, on the three major compilers (GCC, VC++, clang) this code does not crash and appears to<br>work. That’s because one manifestation of “undefined behavior” can be “<em>happens to do what you expect.</em>”</p><p>Nevertheless, this is undefined so one should be careful.</p><h3>Puzzle 4: Throwing away the dead</h3><pre>// godbolt.org/z/p_QjCR<br>static int gi = 0;<br>void f() {<br> int i = 0;<br> throw &amp;i; // ERROR, why??<br> throw &amp;gi; // OK<br>}</pre><h4>Answer:</h4><p>Unlike a return, the type of a thrown object cannot be carried through function signatures. Therefore, do not throw a Pointer with a lifetime other than static.</p><h3>References</h3><ol><li><a href="https://stackoverflow.com/questions/30858850/dereferencing-a-temporary-unique-ptr">https://stackoverflow.com/questions/30858850/dereferencing-a-temporary-unique-ptr</a></li><li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1179r0.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1179r0.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc13ed56f67a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/modern-c-puzzles-fc13ed56f67a">Few Modern C++ Puzzles</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutines and their introduction in C++]]></title>
            <link>https://medium.com/pranayaggarwal25/coroutines-in-cpp-15afdf88e17e?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/15afdf88e17e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Sat, 30 May 2020 12:46:11 GMT</pubDate>
            <atom:updated>2020-06-01T13:00:47.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coroutines and C++20</h3><p>Let’s discuss what coroutines are in general and how C++20 is introducing them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qg0kAy5Zjb9DiXaU.jpeg" /></figure><h3>Table of Contents</h3><p>1. Prerequisite Terminology<br>2. What are coroutines?<br>3. Coroutines vs Subroutines?<br>4. Coroutines vs Threads<br>5. Applications of coroutines<br>6. Example in Python<br>7. How to simulate coroutines in traditional C++<br>8. Coroutines in C++20<br>9. Restrictions</p><h3>Prerequisite Terminology</h3><ol><li><strong>Cooperative Multitasking (a.k.a non-preemptive multitasking) </strong>— If multitasking participant process or thread voluntarily let go of control periodically or when idle or logically blocked. This type of multitasking is called <em>“cooperative”</em> because all programs must cooperate for the entire scheduling scheme to work.</li><li><strong>Subroutine</strong> — Any regular function that you write is a subroutine.</li></ol><h3>What are Coroutines?</h3><p><strong>Coroutines</strong> are stackless functions designed for enabling co-operative Multitasking, by allowing execution to be suspended and resumed.</p><p><strong>Coroutines</strong> suspend execution by returning to the caller and the data that is required to resume execution is stored separately from the stack. This allows for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks), and also supports algorithms on lazy-computed infinite sequences and other uses.</p><p>This is why coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions, event loops, state machines, and pipes.</p><h3>Coroutines vs Subroutines?</h3><ul><li>With subroutines, execution begins at the start and finished on exit.</li><li>Subroutines are special cases of coroutines. Any subroutine can be translated to a coroutine which does not call ‘yield’ (relinquish control).</li><li>Subroutines only return once and don&#39;t hold the complete state between invocations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*u8LQUT-o3R32MBgP.jpg" /></figure><p>In contrast —</p><ul><li>Coroutines can exit by calling other coroutines, which may later return to the point where they were invoked in the original coroutine; from the coroutine’s point of view, it is actually not exiting but calling another coroutine.</li><li>A coroutine instance holds state and varies between invocations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYDtHHWQDCvDt3XZAkNVoQ.png" /></figure><h3>Coroutines vs Threads</h3><ol><li>Coroutines are designed to be performing as lightweight threads.</li><li><strong>Coroutines provide concurrency but not parallelism [Important!]</strong></li><li>Switching between coroutines need not involve any system/blocking calls so no need for synchronization primitives such as mutexes, semaphores.</li></ol><p>Thus coroutines —</p><ol><li>provide asynchronicity and resource locking isn&#39;t needed.</li><li>are useful in functional programming techniques.</li><li>increase locality of reference.</li></ol><h3>Applications of Coroutines</h3><ol><li><strong>Actor Model</strong>: They are very useful to implement the actor model of concurrency. Each actor has its own procedures, but they give up control to the central scheduler, which executes them sequentially.</li><li><strong>Generators</strong>: It is useful to implement generators that are targeted for streams particularly input/output and for traversal of data structures.</li><li><strong>Reverse Communication</strong>: They are useful to implement reverse communication which is commonly used in mathematical software, wherein a procedure needs the using process to make a computation.</li></ol><p><strong>Example 1— </strong>To read a file and parse it while finding (matching) some meaningful data, you can either read step by step at each line, which is fine. You may also load the entire content in memory, which won’t be recommended for large text.</p><p>Coroutines are there to throw away the stack concept completely. Stop thinking of one process as the caller and the other as the callee, and start thinking of them as <strong>cooperating equals</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*DaO1S9QPlS2HOrhA" /><figcaption>Execution flow for reading a file and finding text</figcaption></figure><p><strong>Example 2 — Y</strong>ou have a consumer-producer relationship where one routine creates items and adds them to a queue and another removes items from the queue and uses them. For reasons of efficiency, you want to add and remove several items at once. The pseudo-code might look like this:</p><pre><em>var</em> q := new queue</pre><pre><strong>coroutine</strong> produce<br>    <strong>loop</strong><br>        <strong>while</strong> q is not full<br>            create some new items<br>            add the items to q<br>        <strong>yield</strong> to consume</pre><pre><strong>coroutine</strong> consume<br>    <strong>loop</strong><br>        <strong>while</strong> q is not empty<br>            remove some items from q<br>            use the items<br>        <strong>yield</strong> to produce</pre><p>The queue is then completely filled or emptied before yielding control to the other coroutine using the <em>yield</em> command.</p><p>(This example is often used as an introduction to multithreading, two threads are not a must need for this).</p><h3>An example in Python</h3><p>If you have used Python, you may know that there is a keyword called yield that allows loop back and forth between the caller and the called function until the caller is not done with function or the function terminates because of some logic it is given.</p><pre># A Python program to generate numbers in a range using yield</pre><pre><strong>def</strong> rangeN(a, b):<br>  i <strong>=</strong> a </pre><pre><strong>  while</strong> (i &lt; b):<br>    <strong>yield</strong> i<br>    i <strong>+=</strong> 1  # Next execution resumes from this point</pre><pre><strong>for</strong> i <strong>in</strong> rangeN(1, 5):<br>  print(i)</pre><pre>// Output<br>1<br>2<br>3<br>4<br>5</pre><h3>How to simulate coroutines in traditional C++</h3><p>To simulate coroutines in traditional C++ is challenging as for every response to a function call, there is a stack being initialized that keeps track of all its variables and constants and gets destroyed when the function call ends.</p><p>For the same range example, to simulate a simple switch coroutine suspend-resume we can do something like —</p><pre><strong>// A bad simulation of coroutine, no state saving<br></strong>#include&lt;iostream&gt;</pre><pre>int range(int a, int b) <br>{ <br>  static long long int i = a-1;<br>  for (;i &lt; b;) <br>  {  <br>   return ++i; <br>  } <br>  return 0; <br>}</pre><pre>int main() <br>{ <br> int i;</pre><pre> for (; i=range(1, 5);) <br>   std::cout &lt;&lt; i &lt;&lt; &#39;\n&#39;;<br> return 0; <br>}</pre><p>However, this doesn’t hold good for coroutines criteria of saving/resuming from the saved state :(</p><pre><strong>// A better simulation of coroutine, state saving!!<br></strong>#include&lt;iostream&gt;</pre><pre>int range(int a, int b) <br>{ <br>  <strong>static</strong> <strong>long</strong> <strong>long</strong> <strong>int</strong> i;<br>  <strong>static</strong> <strong>int</strong> state = 0;</pre><pre><strong>  switch</strong> (state)<br>  {<br>    <strong>case</strong> 0: /* start of function */<br>        state = 1;</pre><pre><strong>        for</strong> (i = a; i &lt; b; i++)<br>        {<br>         <strong>return</strong> i; <strong>/* Returns control */</strong></pre><pre><strong>    case</strong> 1:; <strong>/* resume control straight after the return */</strong></pre><pre>        }<br>  }<br>  state = 0;<br>  return 0;<br>}</pre><pre>int main() <br>{ <br> int i;</pre><pre>for (; i=range(1, 5);) <br>   std::cout &lt;&lt; i &lt;&lt; &#39;\n&#39;;<br> return 0; <br>}</pre><h3>Coroutines in C++20</h3><p>In c++20, coroutines are coming. A function is a coroutine if its definition does any of the following:</p><ul><li>uses the co_awaitoperator to suspend execution until resumed.</li><li>uses the keyword co_yield to suspend execution returning a value.</li><li>uses the keyword co_return to complete execution.</li></ul><p>Let’s take a similar example to get a range.</p><p>For the simplicity of this post, let’s assume a generator template is something that exists already and can be used to generate a range,</p><p>(This blog post from Microsoft <a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/october/c-from-algorithms-to-coroutines-in-c"><em>https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/october/c-from-algorithms-to-coroutines-in-c</em></a> is amazing regarding the generator pattern details)</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;</pre><pre><strong>// Coroutine gets called on need</strong></pre><pre>generator&lt;<strong>int</strong>&gt; generateNumbers(<strong>int</strong> begin, <strong>int</strong> inc = 1) {<br>  <br>  <strong>for</strong> (<strong>int</strong> i = begin;; i += inc) {<br>    co_yield i;<br>  }<br>  <br>}<br><br><strong>int</strong> main() {<br><br>    std::cout &lt;&lt; std::endl;<br><br>    <strong>const</strong> <strong>auto</strong> numbers= generateNumbers(-10);     <br>  <br>    <strong>for</strong> (<strong>int</strong> i= 1; i &lt;= 20; ++i) <br>        std::cout &lt;&lt; numbers &lt;&lt; &quot; &quot;; <strong><em>// Runs finite = 20 times</em></strong><br>  <br>                                                         <br>    <strong>for</strong> (<strong>auto</strong> n: generateNumbers(0, 5)) <strong>// Runs infinite times</strong><br>         std::cout &lt;&lt; n &lt;&lt; &quot; &quot;; <em>// (3)</em><br><br>    std::cout &lt;&lt; &quot;<strong>\n\n</strong>&quot;;<br><br>}</pre><p>We’ll cover more about coroutines later as it gets better documented and evolved.</p><h3>Restrictions</h3><p>Every coroutine in C++ has some restrictions noted below. So coroutines —</p><ol><li><strong>Can’t return</strong> with <a href="https://en.cppreference.com/w/cpp/language/variadic_arguments">variadic arguments</a></li><li><strong>Can’t return</strong> using plain “return”</li><li><strong>Can’t return</strong> <a href="https://en.cppreference.com/w/cpp/language/function">placeholder</a> (auto or Concept)</li><li><strong>Can’t be</strong> constexpr functions.</li><li><strong>Can’t be</strong> constructors or destructors.</li><li><strong>Can’t be</strong> the main function.</li></ol><h4>References</h4><ol><li><a href="https://en.cppreference.com/w/cpp/language/coroutines">https://en.cppreference.com/w/cpp/language/coroutines</a></li><li><a href="https://www.xenonstack.com/insights/coroutines/">https://www.xenonstack.com/insights/coroutines/</a></li><li><a href="https://stackoverflow.com/questions/48106252/why-threads-are-showing-better-performance-than-coroutines">https://stackoverflow.com/questions/48106252/why-threads-are-showing-better-performance-than-coroutines</a></li><li><a href="https://www.modernescpp.com/index.php/c-20-coroutines-the-first-overview">https://www.modernescpp.com/index.php/c-20-coroutines-the-first-overview</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve!!<br>Please check out my <a href="https://medium.com/pranayaggarwal25">other articles</a> and <a href="http://pranayaggarwal.github.io/">website</a>, Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15afdf88e17e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/coroutines-in-cpp-15afdf88e17e">Coroutines and their introduction in C++</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using custom deleters with shared_ptr and unique_ptr in C++]]></title>
            <link>https://medium.com/pranayaggarwal25/custom-deleters-with-shared-ptr-and-unique-ptr-524bb7bd7262?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/524bb7bd7262</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Fri, 29 May 2020 16:18:25 GMT</pubDate>
            <atom:updated>2023-08-18T13:48:34.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using custom deleter with smarshared_ptr and unique_ptr in C++</h3><p>How to use a custom deleter with an unique_ptr and shared_ptr</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*doMK1rnrcwhJmTks" /></figure><p><strong>Related post:</strong> <a href="https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc">https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc</a></p><h3>Table of Contents</h3><ol><li>Introduction</li><li>The true unknown face of smart pointers</li><li>What is std::default_delete indeed?</li><li>Ways to specify custom deleters</li><li>Using custom deleter with shared_ptr</li><li>Using custom deleter with unique_ptr</li><li>Storage of custom deleters</li><li>Restrictions that come with custom deleters</li></ol><h3>Introduction</h3><p>Why and when would we need something like that?</p><p><strong>Case 1: </strong>In order to fully delete an object sometimes, we need to do some additional action. What if performing “delete” (that smart pointers do automatically)is not the only thing which needs to be done before fully destroying the owned object.</p><p><strong>Case 2: </strong>We can’t bind a shared_ptr or unique_ptr to a stack-allocated object, because calling delete on it would cause undefined behaviour.</p><p><strong>Case 3: </strong>Mix of programming languages code, such as C++ with Obj-C++. As objective-c may need a complex release mechanism for its data types such as calling <a href="https://developer.apple.com/documentation/corefoundation/1521153-cfrelease">CFRelease</a>, we would be in need of a custom deleter.</p><p><strong>Case 4: </strong>In C where, when you wrap FILE*, or some kind of a C style structure free(), custom deleters may be useful.</p><p>and a few other cases.</p><h3>The true unknown face of smart pointers</h3><h4>std::unique_ptr</h4><p>The complete type of <strong><em>std::unique_ptr</em></strong> has a second template parameter, its deleter that has a default type std::default_delete&lt;T&gt; .<br>What is that?? No need to worry, We’ll cover this together :)</p><pre>template&lt; class T, <strong>class Deleter = std::default_delete&lt;T&gt;</strong> &gt; <br>class unique_ptr;<br>// Manages a single object</pre><pre>template &lt; class T, <strong>class Deleter</strong>&gt; <br>class unique_ptr&lt;T[], Deleter&gt;;<br>// Manages a dynamically-allocated array of objects </pre><p>std::default_delete&lt;T&gt; is a <strong>function object</strong> (a.k.a f<strong>unctor</strong>) that calls delete on the object when invoked. This is only the default type for invoking Deleter and it can be replaced with a custom deleter.</p><p>The invocation is done using operator() on the Deleter.</p><h4>std::shared_ptr</h4><p>You can pass any callable thing (lambda, functor) as deleter while constructing a shared pointer in the constructor as an additional argument.</p><pre>template&lt; class Y, class Deleter &gt;<br>shared_ptr( Y* ptr, Deleter d );</pre><pre>// One of the overloads of shared_ptr construction</pre><p>thus specifying custom deleter with std::shared_ptr is comparatively easy.</p><p>On ref count reaches zero, the shared_ptr uses the <a href="https://en.cppreference.com/w/cpp/language/delete">delete-expression</a> i.e. delete ptr .</p><p>Also since C++17 —</p><pre>// shared_ptr can be used to manage a dynamically allocated array<br>// since C++17 by specifying template argument with T[N] or T[]. So // you may write</pre><pre>shared_ptr&lt;int[]&gt; myShared(new int[10]);</pre><h3>What is std::default_delete indeed?</h3><p>This is defined in &lt;memory&gt; header.</p><pre>template&lt; class T &gt; struct default_delete;</pre><pre>template&lt; class T &gt; struct default_delete&lt;T[]&gt;;</pre><ol><li>The non-specialized default_delete uses <strong><em>delete</em></strong> to deallocate memory for a single object.</li><li>A partial specialization for array types that uses <strong><em>delete[]</em></strong> is also provided.</li></ol><h4>Members:</h4><ol><li>Constructor — can be default or templated.</li></ol><pre><strong>constexpr default_delete() noexcept = default; </strong>// default</pre><pre><strong>template &lt;class U&gt;<br>default_delete( const default_delete&lt;U&gt;&amp; d ) noexcept;</strong> // templated<br>// <em>Constructs a </em><em>std::default_delete object from another.<br>// Overload resolution if </em><em>U* is implicitly convertible to </em><em>T*.</em></pre><p><strong>2. operator() — </strong>overload for the operator() is needed for the callability of struct/class as its a function object( or functor).<br>At the point in the code where, this operator() is called, the type must be complete and defined.</p><p>Examples:</p><pre><strong>Example 1:<br></strong>{<br>    std::unique_ptr&lt;int&gt; ptr(new int(5));<br>}   <br>// unique_ptr&lt;int&gt; uses default_delete&lt;int&gt;</pre><pre>====================================================================</pre><pre><strong>Example 2:<br></strong>{<br>   std::unique_ptr&lt;int[]&gt; ptr(new int[10]);<br>}  <br>// unique_ptr&lt;int[]&gt; uses default_delete&lt;int[]&gt;</pre><pre>====================================================================</pre><pre><strong>Example 3:</strong><br>// default_delete can be used anywhere a delete functor is needed<br>std::vector&lt;int*&gt; v;</pre><pre>for(int n = 0; n &lt; 100; ++n)<br>   v.push_back(new int(n));</pre><pre>std::for_each(v.begin(), v.end(), <strong>std::default_delete&lt;int&gt;()</strong>);<br>// Constructing the function object to be called</pre><pre>====================================================================</pre><pre><strong>Example 4:</strong></pre><pre>{<br>    std::shared_ptr&lt;int&gt; shared_bad(new int[10]); <br>} <br>// the destructor calls delete, undefined behavior as it&#39;s an array<br> <br>{<br>    std::shared_ptr&lt;int&gt; shared_good(new int[10], std::default_delete&lt;int[]&gt; ());<br>} // <strong>the destructor calls delete[], ok</strong></pre><pre>====================================================================</pre><pre><br><strong>Example 5: (Valid only C++17 onwards)<br></strong>{<strong><br></strong>shared_ptr&lt;int[]&gt; shared_best(new int[10]);<br>}<br>// <strong>the destructor calls delete[], awesome!!</strong></pre><pre>====================================================================</pre><h3>Ways to specify custom deleters</h3><ol><li>std::function — Heavy size contribution ( ~32 bytes! on x64)</li><li>Function pointer — Just a pointer</li><li>Stateless functor / Stateless Lambda — None.</li><li>Stateful functor / Stateful Lambda — sizeof(functor or lambda)</li></ol><h3>Using custom deleter with shared_ptr</h3><p>Examples —</p><h4>1. Use a proper functor —</h4><p>(Requires custom deleter for array only Prior to C++17)</p><pre>// declare the function object</pre><pre>template&lt; typename T &gt;<br>struct array_deleter<br>{<br>  void operator ()( T const * p)<br>  { <br>    delete[] p; <br>  }<br>};</pre><pre>// and use shared_ptr as follows by constructing function object<br>std::shared_ptr&lt;int&gt; sp(new int[10], <strong>array_deleter&lt;</strong>int<strong>&gt;</strong>());</pre><h4>2. Use a plain lambda</h4><p>std::shared_ptr&lt;MyType&gt; sp(new int[10], [](int *p) { delete[] p; });</p><h4>3. Use default_delete (Only valid for array types before C++17)</h4><p>std::shared_ptr&lt;int&gt; sp(new int[10], std::default_delete&lt;int[]&gt;());</p><p><strong>Note: </strong>delete ptr is same as specifying default_delete&lt;T&gt;{}ptr .</p><h3>Using custom deleter with unique_ptr</h3><p>With unique_ptr there is a bit more complication. The main thing is that a deleter type will be part of unique_ptr type.</p><p>By default we get std::default_delete so here are some examples —</p><p>For a class <strong><em>MyType</em></strong></p><pre>class MyType {</pre><pre>  // ...<br>  // ...</pre><pre>};</pre><pre>void deleter(MyType*) {<br>// ...<br>}</pre><pre>====================================================================</pre><pre><br><strong>// 1. std::function <br></strong>std::unique_ptr&lt;MyType, std::function&lt;void (MyType*)&gt;&gt; u1(new MyType(), deleter);</pre><pre>OR </pre><pre>std::unique_ptr&lt;MyType, decltype(&amp;deleter)&gt; u1(new MyType(), deleter); </pre><pre><strong>// 2nd argument in unique_ptr object construction is required. <br>It is optional ONLY in case a custom deleter is already wrapped as functor object (Point #3 below), as function objects are created by default in those cases.<br>// As a good practice it&#39;s always useful to pass second argument here. </strong></pre><pre>====================================================================</pre><pre><strong>// 2. Function pointer</strong><br>std::unique_ptr&lt;MyType, void (*)(MyType *)&gt; u2(new MyType(), deleter);</pre><pre>====================================================================</pre><pre>// A stateless functor<br>struct MyTypeDeleterFunctor {  <br>    void operator()(MyType* p) {<br>        // ...<br>    }<br>};</pre><pre><strong>// 3. Stateless functor</strong><br>std::unique_ptr&lt;MyType, MyTypeDeleterFunctor&gt;u3(new MyType());<br>// deleter type is not a reference hence gets copied</pre><pre>MyTypeDeleterFunctor functor;<br>std::unique_ptr&lt;MyType, MyTypeDeleterFunctor&amp;&gt;u3(new MyType(), functor );</pre><pre>// deleter type is a reference hence gets copied</pre><pre>====================================================================</pre><pre>// 4. <strong>The lambda way</strong></pre><pre>auto deleter = [](MyType*){ ... }</pre><pre>std::unique_ptr&lt;MyType, void (*)(MyType *)&gt;&gt; u1(new MyType(), deleter); <br>// OR<br>std::unique_ptr&lt;MyType, decltype(deleter)&gt;&gt; u1(new MyType(), deleter);</pre><pre>// Mind the decltype(deleter) here, without a <strong>&amp; </strong>since deleter isn&#39;t a function here, rather a lambda</pre><h3>Storage of custom deleters</h3><p><strong>For shared_ptr<br></strong>When you use a custom deleter it won’t affect the size of your shared_ptr type. If you remember, shared_ptr size should be roughly 2 x sizeof(ptr) so where does this deleter hide?</p><p>As we know, shared_ptr consists of two things: pointer to the object and pointer to the control block (that contains ref count). Inside the control block structure of shared_ptr, there is a space for custom deleter and allocator.</p><p><strong>For unique_ptr<br></strong>unique_ptr is small and efficient; the size is one pointer so where is the custom allocator hide in this case?</p><p>The deleter is part of the type of unique_ptr. And since the functor/lambda that is stateless, its type fully encodes everything there is to know about this without any size involvement. Using function pointer takes one pointer size and std::function takes even more size.</p><blockquote>The shared_ptr always stores a deleter, this erases the type of the deleter, which might be useful in APIs. The disadvantages of using shared_ptr over unique_ptr include a higher memory cost for storing the deleter and a performance cost for maintaining the reference count.</blockquote><p><strong>Trivia:</strong> The size of weak_ptr is the same as that of shared_ptr. Weak pointer points to the same control block as it’s shared pointer. When a weak_ptr is created, destroyed, or copied a second reference count (weak pointer reference count) is manipulated. Weak count is connected with object storage deallocation (Refer prerequisite <a href="https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc">talk</a>)</p><h3>Restrictions that come with custom deleter</h3><h4>Can’t use make_shared with shared_ptr</h4><p>Unfortunately, you can pass a custom deleter only in the constructor of shared_ptr there is no way to use make_shared. This might be a bit of disadvantage (Refer prerequisite <a href="https://medium.com/pranayaggarwal25/a-tale-of-two-allocations-f61aa0bf71fc">talk</a>)</p><p>One can use <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr/allocate_shared">allocate_shared</a> and custom allocator and deleter, but that’s too complex to be covered in this article.</p><h4>Can’t use make_unique with unique_ptr</h4><p>Similarly as with shared_ptr you can pass a custom deleter only in the constructor of unique_ptr and thus you cannot use make_unique.</p><h3>References:</h3><ol><li><a href="https://www.reddit.com/r/cpp/comments/4gu77b/code_and_graphics_custom_deleters_for_c_smart/">https://www.reddit.com/r/cpp/comments/4gu77b/code_and_graphics_custom_deleters_for_c_smart/</a></li><li><a href="https://www.bfilipek.com/2016/04/custom-deleters-for-c-smart-pointers.html">https://www.bfilipek.com/2016/04/custom-deleters-for-c-smart-pointers.html</a></li><li><a href="https://en.cppreference.com/w/cpp/memory/default_delete">https://en.cppreference.com/w/cpp/memory/default_delete</a></li><li><a href="https://stackoverflow.com/questions/51255583/shouldnt-stdshared-ptr-use-stddefault-delete-by-default">https://stackoverflow.com/questions/51255583/shouldnt-stdshared-ptr-use-stddefault-delete-by-default</a></li><li><a href="https://www.programming-books.io/essential/cpp/using-custom-deleters-to-create-a-wrapper-to-a-c-interface-e8fe82bfeff74f699dc810b6cd5ce57a">https://www.programming-books.io/essential/cpp/using-custom-deleters-to-create-a-wrapper-to-a-c-interface-e8fe82bfeff74f699dc810b6cd5ce57a</a></li></ol><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. Please feel free to drop any comments to improve this article.<br>Please check out my <a href="https://medium.com/pranayaggarwal25">other articles</a> and <a href="http://pranayaggarwal.github.io/">website</a>, Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524bb7bd7262" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/custom-deleters-with-shared-ptr-and-unique-ptr-524bb7bd7262">Using custom deleters with shared_ptr and unique_ptr in C++</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal Reference and Perfect forwarding]]></title>
            <link>https://medium.com/pranayaggarwal25/universal-reference-perfect-forwarding-5664514cacf9?source=rss-8e13fd63c187------2</link>
            <guid isPermaLink="false">https://medium.com/p/5664514cacf9</guid>
            <category><![CDATA[reference]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[universal]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Pranay Kumar]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 12:58:25 GMT</pubDate>
            <atom:updated>2020-04-11T13:02:05.985Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Also known as Forwarding reference</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*wi8CKG57G8q3-woE.gif" /></figure><p><strong>Prerequisites:</strong> <a href="https://medium.com/pranayaggarwal25/rvalue-references-e99dfd3933ff">Rvalue references</a></p><h4>Table of Contents:</h4><p>1. Introduction<br>2. The double life of “&amp;&amp;”<br>3. How to identify a Universal Reference<br>4. Universal Reference in templates<br>5. Universal Reference in auto<br>6. How does the magic of Univeral Reference work?<br>7. Handle with care<br>8. What is the need? The perfect forwarding problem<br>9. How to work with Universal References?<br>10. Universal Reference in “typedef”<br>11. Universal Reference in “decltype”<br>12. The ultimate Truth</p><h3>Introduction</h3><blockquote>Every rvalue ref is denoted by ‘&amp;&amp;’ but vice versa is not true.</blockquote><p>Rvalue reference ⇒ “&amp;&amp;” <br>“&amp;&amp;” <strong>⇏</strong> Rvalue reference.</p><p>“&amp;&amp;” in source code though may have the syntactic <em>appearance</em> of an rvalue reference (“&amp;&amp;”), but the meaning of an lvalue reference (“&amp;”).</p><h3>The double Life of “&amp;&amp;”</h3><p>There is a double life that “&amp;&amp;” lives on and we need to understand that. Let’s see some examples —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*BejVgArr4hHBus4hS3aoSw.png" /><figcaption><strong>The double life of “&amp;&amp;”</strong></figcaption></figure><p>In<strong> </strong>“<strong>type</strong><strong>&amp;&amp;</strong>”<strong>, </strong>&amp;&amp; means either -</p><p><strong>1. Rvalue reference — </strong>As you’d expect.<strong><br></strong> i)<strong> </strong>Binds rvalues only<br>ii) Facilitates the moving of objects.</p><p><strong>2. Forwarding reference</strong> (a.k.a <strong>Universal reference</strong>) — The mentioned type is a special type of reference that can bind anything &amp; everything.</p><p>i) Universal reference can mean both Rvalue reference and Lvalue reference.<br>ii) May facilitate copying, may facilitate moving.<br>iii) Syntactically “type&amp;&amp;” but semantically “type&amp;&amp;” or “type&amp;”.</p><blockquote>Universal reference can bind lvalues, rvalues (be it const or non-const) thus everything.</blockquote><h3>How to identify a Universal Reference</h3><blockquote><em>If </em><em>T is getting deduced and variable / parameter type is unqualified</em><strong><em>T&amp;&amp; </em></strong><em>, then only it’s a Universal Reference. Here if </em><em>T has already been deduced, that means no Universal Reference, plain simple rvalue reference.</em></blockquote><blockquote><strong>Not all </strong><strong><em>T&amp;&amp; are Universal Reference.</em></strong></blockquote><p>There are 4 possible contexts — <br>1. Function template parameters —</p><pre>template&lt;typename MyType&gt;<br> void f(MyType<strong>&amp;&amp;</strong> param);  // <strong>&amp;&amp; ≡ rvalue reference</strong></pre><p>2. <strong>auto</strong> declarations auto&amp;&amp; var2 = var1;<br>3. typedef declarations<br>4. decltype expressions</p><p>Out of the above 4, the first two are the most commonly occurring cases. As we have seen in the rule, type deduction is must so —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*hxu81px55zDERu49GRh3bA.png" /><figcaption>Understanding Type Deduction</figcaption></figure><h3>Univeral references in Templates</h3><pre>template&lt;typename T&gt;<br>void f(T<strong>&amp;&amp;</strong> param)<br>{<br> std::cout&lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; std::endl;<br>}</pre><p>So calling function ‘f’ in different ways will produce different results.</p><p><strong>Example 1:</strong> Calling function ‘f’</p><pre>Widget w;<br>f(w); <br><strong>// T&amp;&amp; </strong>forwarding reference<strong> </strong>will be resolved as <strong>Lvalue Ref<br>// Thus instantiating void f(Widget&amp;) out of the template</strong></pre><pre>void f(T&amp;&amp;) [with T = Widget&amp;].  // Printed</pre><p><strong>Example 2: </strong>adding const also —</p><pre>const Widget cw;<br>f(cw); <br><strong>// T&amp;&amp; </strong>forwarding reference<strong> </strong>will be resolved as <strong>Lvalue Ref to const<br>// Thus instantiating void f(const Widget&amp;) out of the template</strong></pre><pre>void f(T&amp;&amp;) [with T = const Widget&amp;].  // Printed</pre><p><strong>Example 3:</strong> passing rvalues —</p><pre>f(Widget());<br><strong>// T&amp;&amp; </strong>forwarding reference will be resolved as <strong>Rvalue Ref<br>// Thus instantiating void f(Widget&amp;&amp;) out of the template</strong></pre><pre>void f(T&amp;&amp;)[with T = Widget]  <br>// Printed, Why?? explained later in Table 2</pre><p><strong>Example 4: </strong>adding const with rvalues</p><pre>const Widget cw;<br>f(std::move(cw));<br><strong>// </strong>T&amp;&amp;<strong> </strong>forwarding reference will be resolved as<strong> Rvalue Ref to const<br>// Thus instantiating void f(const Widget&amp;&amp;) out of the template</strong></pre><pre>void f(T&amp;&amp;)[with T = const Widget] <br>// Printed, Why? Explained later in Table 2</pre><h3>Univeral references in auto</h3><p>auto&amp;&amp; var = 10; // 10 is value hence var being Universal reference, <strong>resolves to an rvalue reference. Type of var is “int &amp;&amp;”.</strong></p><p>std::vector&lt;int&gt; vec;<br>auto&amp;&amp; var = vec[0]; // vector[] is int&amp; hence var being Universal reference,<br><strong>resolves to an Lvalue reference. Type of var is “int&amp;”.</strong></p><p>int i = 10;<br>const auto&amp;&amp; var = i; // Not a Universal Reference hence Error!!</p><h3>How does the magic of Univeral Reference work?</h3><p>In pre-11 C++, it was not allowed to take a reference to a reference: something like A&amp; &amp; would cause a compile error. C++11, by contrast, introduces the following <strong>R<em>eference collapsing rules</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMsWQ7At7DM5eNqZt9QcQg.png" /><figcaption><strong>Table 1: Reference Collapsing Rules</strong></figcaption></figure><p>Reference collapsing is magic that enables Universal references to work. These rules are basically a logical AND of Lvalue ref implying ‘0’ (zero) with Rvalue ref implying ‘1’(one)</p><blockquote>Reference Collapsing Rule#1: Lvalues are infectious.</blockquote><p>So basically in the above template examples of Univeral reference —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNPrhEdAboP8AubgIxuhdg.png" /></figure><p><strong>Table 2: Reference Collapsing Rules for template Examples 1- 4</strong></p><p>Columns with color code orange here don’t have &amp;&amp; for T. The reason behind that is —</p><blockquote>“In template / auto type deduction, references become non-references before lvalue / rvalue analysis. Once deduction takes place, analysis occurs and if lvalue, reference is put back on”</blockquote><p>Also, looking at the table values leads to another rule which is —</p><blockquote>Reference Collapsing Rule#2: const volatile qualifiers of original type are reserved.</blockquote><p><strong>Remember, It’s still impossible to declare a reference to reference explicitly. The compiler can do it, you can’t!!</strong></p><h3>Handle with care…</h3><ol><li>The thing with overloading used with universal reference is that it almost always turns out differently than expected.</li></ol><pre>=========================================================<br>class MyWidget {<br>    ...</pre><pre>template&lt;typename T&gt;   // <strong>Version 1</strong><br>    void <strong>f</strong>(const T&amp; rhs);  // Best match for const Lvalue Ref</pre><pre>template&lt;typename T&gt;   // <strong>Version 2 </strong><br>    void <strong>f</strong>(T&amp;&amp; rhs);   //<strong> universal reference, can handle everything</strong><br>    <br>    ...<br>};</pre><pre>=========================================================</pre><pre>MyWidget m;<br>const MyWidget cm;</pre><pre>f(m);            // <strong>Case 1, Calls Version 2!!</strong><br>f(std::move(m)); // Case 2, Calls Version 2<br>f(cm);           <strong>// </strong>Case 3,<strong> </strong>Calls Version 1<br>f(std::move(m)); // Case 4, Calls Version 2</pre><pre>=========================================================</pre><p>This happens as Version 2 of ‘f’ with Universal reference can resolve to anything if needed and thus is a better match for Lvalue Reference. However, if an exact match is found like in case 3, there Version 1 of ‘f’ is called.</p><p>2. Another precaution with Universal Reference is that you can’t forward NULL as null pointers because that will be treated as int 0 = (zero). Another reason to use std::nullptr !!</p><p>3. If braced initializers are passed, the compiler can not deduce the type so you should explicitly mention the type.</p><h3>What is the need? The perfect forwarding problem</h3><p>Let func(E1 E2, ... En); be an arbitrary function call with generic parameters E1, E2, …, En. We’d like to write a function wrapper such that wrapper(E1 E2, ... En) is equivalent to func(E1 E2, ... En) .</p><p>The first approach that comes to mind is —</p><pre>template &lt;typename T1, typename T2&gt;<br>void wrapper(T1 e1, T2 e2) {<br>    func(e1, e2);<br>}</pre><p>But this will not work if ‘func’ accepts its param by reference since ‘wrapper’ is passing its local copies. We can add another definition.</p><pre>template &lt;typename T1, typename T2&gt;<br>void wrapper(T1&amp; e1, T2&amp; e2) {<br>    func(e1, e2);<br>}</pre><p>but what if we would want to pass rvalues also? What about const-ness?<br>As you see this will be an exponential problem. Brute force solution —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnR_CDZLMixWJChrha8nLg.png" /><figcaption>These are just lvalue versions, rvalue versions will also be needed.</figcaption></figure><p>Hence there was a need for perfectly forwarding whatever parameter is received and that is achievable by Universal references.</p><h3>How to work with Universal References?</h3><blockquote>A type in independent of lvalueness and rvalueness</blockquote><p>There are lvalues of type int (e.g., variables declared to be ints), and there are rvalues of type int (e.g., literals like 10)</p><pre>Widget&amp;&amp; var1 = makeWidget()   // var1 is an lvalue, but<br>// its type is rvalue reference (to Widget)</pre><p>As with Rvalue references, we use std::move<em>, with Universal references we should always use </em><a href="https://en.cppreference.com/w/cpp/utility/forward">std::forward&lt;T&gt;</a> present in &lt;utility&gt; header which takes care of copy in case of Lvalue Ref and move in case of Rvalue Ref.</p><p>std::forward keeps the reference type of x. So:</p><ul><li>If x is an rvalue reference then std::forward is = std::move,</li><li>If x is an lvalue reference then std::forward doesn’t do anything.</li></ul><p>So for the previous example of ‘wrapper’ function on func(E1 E2, ... En)-</p><pre>template &lt;typename T1, typename T2&gt;<br>void wrapper(T1&amp;&amp; e1, T2&amp;&amp; e2) {<br>    func(std::forward&lt;T1&gt;(e1), std::forward&lt;T2&gt;(e2));<br>}</pre><pre>// Awesome!!</pre><blockquote>std::forward is a conditional cast but std::move is an unconditional cast.</blockquote><p>Applications of perfect forwarding are std::make_shared , std::make_unique , vector::emplace_back etc.</p><h3>Universal references in “typedef”</h3><pre>template&lt;typename T&gt;<br>class Widget<br>{<br>// ...<br>}</pre><pre>=========================================================</pre><pre>Widget&lt;int&amp;&gt; w;</pre><pre><strong>typedef Widget&amp;&amp; UniRefToWodget;</strong></pre><pre>UniRefToWodget &amp;v1 = w; <br>// Reference collapsing, v1&#39;s type is <strong>Widget&amp;</strong></pre><pre>const UniRefToWodget &amp;v2 = std::move(w); <br>// Reference collapsing, v2&#39;s type is <strong>const Widget&amp;</strong></pre><pre>UniRefToWodget &amp;&amp;v3 = std::move(w); <br>// Reference collapsing, v3&#39;s type is <strong>Widget&amp;&amp;</strong></pre><h3>Universal References in “decltype”</h3><p>For <em>decltype, </em>Type deduction rule is different.</p><ol><li>decltype(id) ⇒ id’s declared type.</li><li>decltype(non-id lvalue expression) ⇒ Expression’s type, <strong>Lvalue Ref (T&amp;)</strong></li><li>decltype(non-id rvalue expression) ⇒ Expression’s type, <strong>Non-Ref (T)</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*wBdb9YCnAO0VPvwqLWnbJA.png" /><figcaption>decltype and Universal Reference</figcaption></figure><h3>Ultimate Truth</h3><p>“&amp;&amp;” is really Always Rvalue Reference, but due to the magic of Reference collapsing, It can work as a reference that can work with anything hence the fancy name “Universal Reference” a.k.a. “Forwarding Reference”. :)</p><h3>Bonus point : coz you made it till here!!</h3><p>What does std::forward do actually?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLPj-EPcjNl2afshgBLaWw.png" /><figcaption>Implementation of std::forward</figcaption></figure><p><strong>Case 1:</strong> passing lvalues sayint&amp; , T is deduced as int&amp;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3CTuZ7DnDKASZlChPn3rg.png" /><figcaption>Putting T as int&amp;</figcaption></figure><p>After Reference collapsing, std::forward turns into this, which is as good as passing lvalue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMkkMxSVP01Aq-uzj1okmw.png" /><figcaption>The final definition looks like this after Reference collapsing</figcaption></figure><p><strong>Case 2:</strong> passing rvalues sayint&amp;&amp; , T is deduced as int (Why? Read note mentioned after Table 2). Now After applying T as int —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqib7b-jjZtkHYHDf3neZg.png" /><figcaption>The final definition looks like this after Reference collapsing</figcaption></figure><p>std::forward could do the job without <a href="https://en.cppreference.com/w/cpp/types/remove_reference">std::remove_reference</a>. Reference collapsing does the job already, so std::remove_reference&lt;T&gt; is superfluous.</p><p>But it’s there to turn the T&amp;t into a non-deducing context, thus forcing us to explicitly specify the template parameter when calling std::forward .</p><h3>References</h3><ol><li><a href="https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers#NittyGrittyDetails">https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers#NittyGrittyDetails</a></li><li><a href="https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Scott-Meyers-Universal-References-in-Cpp11">https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Scott-Meyers-Universal-References-in-Cpp11</a></li><li><a href="http://thbecker.net/articles/rvalue_references/section_08.html">http://thbecker.net/articles/rvalue_references/section_08.html</a></li><li><a href="https://www.fluentcpp.com/2018/02/06/understanding-lvalues-rvalues-and-their-references/">https://www.fluentcpp.com/2018/02/06/understanding-lvalues-rvalues-and-their-references/</a></li><li><a href="https://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c">https://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c</a></li><li><a href="https://www.slideshare.net/oliora/hot-universal-references-and-perfect-forwarding-82155460">https://www.slideshare.net/oliora/hot-universal-references-and-perfect-forwarding-82155460</a></li><li><a href="http://thbecker.net/articles/rvalue_references/section_01.html">http://thbecker.net/articles/rvalue_references/section_01.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5664514cacf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pranayaggarwal25/universal-reference-perfect-forwarding-5664514cacf9">Universal Reference and Perfect forwarding</a> was originally published in <a href="https://medium.com/pranayaggarwal25">pranayaggarwal25</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>