<?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 Batur Toraman on Medium]]></title>
        <description><![CDATA[Stories by Batur Toraman on Medium]]></description>
        <link>https://medium.com/@toramanbatur?source=rss-63723746880f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Pt9wrc-WQva3j2da</url>
            <title>Stories by Batur Toraman on Medium</title>
            <link>https://medium.com/@toramanbatur?source=rss-63723746880f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:56:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@toramanbatur/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[Mastering C++: Exploring 6 Powerful Idioms for Effective Programming and Best Practices]]></title>
            <link>https://medium.com/@toramanbatur/the-power-of-c-a-deep-dive-into-idioms-and-best-practices-31ab4792563e?source=rss-63723746880f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31ab4792563e</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[idioms]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Batur Toraman]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 16:02:29 GMT</pubDate>
            <atom:updated>2023-03-22T11:06:02.496Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Intro</strong></blockquote><p>C++ is a powerful programming language that allows developers to write high-performance code with low-level control. However, this flexibility can come at the cost of complexity, especially for those new to the language. Advanced C++ idioms can help developers take their skills to the next level by providing powerful abstractions and best practices. In this blog, we’ll explore some of the most popular and widely-used advanced C++ idioms and provide code examples to help you understand how they work in practice. Whether you’re a seasoned C++ developer or just getting started, this blog will provide valuable insights into the world of advanced C++ programming.</p><blockquote><strong>6 Widely Used C++ Idioms You Need to Know</strong></blockquote><ol><li>RAII (Resource Acquisition Is Initialization)</li><li>CRTP (Curiously Recurring Template Pattern)</li><li>SFINAE (Substitution Failure Is Not An Error)</li><li>Perfect forwarding</li><li>Type traits</li><li>Pimpl(Pointer to Implementation)</li></ol><blockquote><strong>1- RAII (Resource Acquisition Is Initialization)</strong></blockquote><p>RAII (Resource Acquisition Is Initialization) is an idiom that allows the automatic management of resources in C++ by acquiring the resource in the constructor of an object and releasing it in the destructor of the same object.</p><p><strong><em>Advantages</em></strong> of RAII:</p><ol><li><strong>Exception-safe Code</strong>: RAII makes it easy to write exception-safe code. If an exception is thrown during the construction of an object, the destructor will be automatically called to release the acquired resource.</li><li><strong>Avoid Memory Leaks:</strong> RAII makes it easy to write code that is resistant to memory leaks. If an object is created to acquire a resource and it goes out of scope, the destructor will be called to release the resource, even if the code has multiple exit points.</li><li><strong>Encapsulating Resource Management:</strong> RAII can improve code clarity and reduce the likelihood of errors by encapsulating resource management in an object.</li></ol><p><strong><em>Disadvantages</em></strong> of RAII:</p><ol><li><strong>Complex Code:</strong> RAII requires that resource management be encapsulated in an object, which can lead to more complex code.</li><li><strong>Releasing Resource: </strong>RAII can make it difficult to manage resources that require multiple steps to acquire or release.</li></ol><p>Here is an example implementation of RAII using a File class that opens a file in its constructor and closes the file in its destructor:</p><pre>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br><br>class File {<br>public:<br>    explicit File(const std::string&amp; filename) : file_(filename) {<br>        if (!file_) {<br>            throw std::runtime_error(&quot;Unable to open file&quot;);<br>        }<br>        std::cout &lt;&lt; &quot;File &quot; &lt;&lt; filename &lt;&lt; &quot; opened.\n&quot;;<br>    }<br><br>    ~File() {<br>        if (file_.is_open()) {<br>            file_.close();<br>            std::cout &lt;&lt; &quot;File closed.\n&quot;;<br>        }<br>    }<br><br>    std::ifstream&amp; get() {<br>        return file_;<br>    }<br><br>private:<br>    std::ifstream file_;<br>};<br><br>int main() {<br>    try {<br>        File file(&quot;example.txt&quot;);<br>        std::string line;<br>        while (std::getline(file.get(), line)) {<br>            std::cout &lt;&lt; line &lt;&lt; &#39;\n&#39;;<br>        }<br>    } catch (const std::exception&amp; e) {<br>        std::cerr &lt;&lt; &quot;Exception: &quot; &lt;&lt; e.what() &lt;&lt; &#39;\n&#39;;<br>    }<br>    return 0;<br>}</pre><p>In this example, the File class takes a filename as a parameter in its constructor and opens the file using an std::ifstream. If the file cannot be opened, a std::runtime_error is thrown. In the destructor of File, the std::ifstream is closed if it is still open. The get() function returns a reference to the std::ifstream so that it can be used to read the file.</p><p>When the File object is created in main(), the file is automatically opened. When the File object goes out of scope at the end of main(), the file is automatically closed. If an exception is thrown during the reading of the file or the file cannot be opened, the File object will be destroyed and the file will be closed before the exception propagates out of main().</p><p>Example output:</p><pre>File example.txt opened.<br>This is an example file.<br>It has multiple lines.<br>The end.<br>File closed.</pre><blockquote>2-CRTP (Curiously Recurring Template Pattern)</blockquote><p>CRTP stands for “Curiously Recurring Template Pattern”. It is a C++ design pattern that involves a base class that is templated on the derived class. The derived class then inherits from the base class using the derived class as the template argument. This pattern allows the base class to use properties and functions of the derived class without requiring dynamic polymorphism.</p><p><strong><em>Advantages</em></strong> of CRTP:</p><ol><li><strong>Performance</strong>: CRTP can offer better performance than traditional runtime polymorphism because the function calls are resolved at compile-time rather than runtime.</li><li><strong>Code Reuse</strong>: CRTP can facilitate code reuse by allowing you to inherit functionality from a base class without incurring the overhead of virtual function calls.</li><li><strong>Encapsulation</strong>: CRTP can help enforce encapsulation by allowing you to specify which members are accessible to the derived classes.</li></ol><p><strong><em>Disadvantages</em></strong> of CRTP:</p><ol><li><strong><em>Code Complexity:</em></strong> CRTP can increase the complexity of your code, particularly if you’re not familiar with the technique. It can also make debugging more difficult.</li><li><strong><em>Limited Runtime Polymorphism</em></strong>: CRTP does not offer the same level of runtime polymorphism as traditional virtual functions, which may limit its usefulness in some cases.</li><li><strong><em>Potential code bloat:</em></strong> If you have a large number of derived classes, CRTP can lead to code bloat because each derived class will generate its own copy of the base class code.</li></ol><p>Here’s an example implementation of CRTP:</p><pre>#include &lt;iostream&gt;<br><br>template&lt;typename Derived&gt;<br>class Base<br>{<br>public:<br>    void printDerivedType()<br>    {<br>        std::cout &lt;&lt; &quot;Derived type: &quot; &lt;&lt; Derived::type() &lt;&lt; std::endl;<br>    }<br><br>    void printBaseType()<br>    {<br>        std::cout &lt;&lt; &quot;Base type&quot; &lt;&lt; std::endl;<br>    }<br>};<br><br>class Derived1 : public Base&lt;Derived1&gt;<br>{<br>public:<br>    static std::string type()<br>    {<br>        return &quot;Derived1&quot;;<br>    }<br>};<br><br>class Derived2 : public Base&lt;Derived2&gt;<br>{<br>public:<br>    static std::string type()<br>    {<br>        return &quot;Derived2&quot;;<br>    }<br>};<br><br>int main()<br>{<br>    Derived1 d1;<br>    Derived2 d2;<br><br>    d1.printDerivedType();<br>    d2.printDerivedType();<br><br>    d1.printBaseType();<br>    d2.printBaseType();<br><br>    return 0;<br>}</pre><p>In this example, we define a base class Base that is templated on the derived type. The printDerivedType function uses the derived type to print out the name of the derived class, while the printBaseType function prints out the name of the base class.</p><p>We then define two derived classes, Derived1 and Derived2, that inherit from Base using CRTP. Each derived class defines a static type function that returns the name of the derived class.</p><p>In the main function, we create instances of Derived1 and Derived2 and call the printDerivedType and printBaseType functions on each instance.</p><p>Example Output:</p><pre>Derived type: Derived1<br>Derived type: Derived2<br>Base type<br>Base type</pre><p>As we can see from the output, the printDerivedType function correctly prints out the name of the derived class for each instance, while the printBaseType function correctly prints out the name of the base class for each instance. This is achieved without using virtual functions or runtime polymorphism, and the function calls are resolved at compile-time.</p><blockquote>3-SFINAE (Substitution Failure Is Not An Error)</blockquote><p>SFINAE stands for “Substitution Failure Is Not An Error”. The idea behind SFINAE is that if a substitution fails during template instantiation (e.g., because a type does not have a certain member function), the compiler will simply move on and try the next available template instead of generating an error. This allows you to write more flexible and generic code by selectively enabling/disabling functions based on the types of their arguments.</p><p><strong><em>Advantages</em></strong> of SFINAE:</p><ol><li><strong>Flexibility</strong>: SFINAE allows you to write more flexible and generic code by selectively enabling/disabling functions based on the types of their arguments.</li><li><strong>Better Error Messages</strong>: SFINAE can result in better error messages, as it allows the compiler to choose a better-matching function rather than simply failing to compile.</li><li><strong>Type Traits</strong>: SFINAE can be used to implement type traits, which are templates that provide compile-time information about the properties of types.</li></ol><p><strong><em>Disadvantages</em></strong> of SFINAE:</p><ol><li><strong>Complexity</strong>: SFINAE can increase the complexity of your code, particularly if you’re not familiar with the technique. It can also make debugging more difficult.</li><li><strong>Limited Readability:</strong> SFINAE can make code harder to read and understand because it involves advanced template metaprogramming techniques that are not always intuitive.</li><li><strong>Compiler-specific Behavior:</strong> SFINAE can behave differently across different compilers, which can make it harder to write portable code.</li></ol><p>Here’s an example implementation of SFINAE:</p><pre>#include &lt;iostream&gt;<br>#include &lt;type_traits&gt;<br><br>template&lt;typename T,<br>    typename std::enable_if&lt;std::is_integral&lt;T&gt;::value&gt;::type* = nullptr&gt;<br>void print(T value)<br>{<br>    std::cout &lt;&lt; &quot;Integral value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>template&lt;typename T,<br>    typename std::enable_if&lt;std::is_floating_point&lt;T&gt;::value&gt;::type* = nullptr&gt;<br>void print(T value)<br>{<br>    std::cout &lt;&lt; &quot;Floating-point value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main()<br>{<br>    int i = 42;<br>    float f = 3.14;<br><br>    print(i);<br>    print(f);<br><br>    return 0;<br>}</pre><p>In this example, we define two overloaded print functions. The first print function is enabled only for integral types, and the second print function is enabled only for floating-point types. We use std::enable_if to selectively enable/disable the functions based on the types of their arguments.</p><p>In the main function, we create an int variable i and a float variable f, and call the print function on each variable.</p><p>Example Output:</p><pre>Integral value: 42<br>Floating-point value: 3.14</pre><blockquote>4-Perfect Forwarding</blockquote><p>Perfect forwarding is a C++ technique that allows you to forward arguments to other functions or templates while preserving their original types and qualifiers. This improves performance by avoiding unnecessary copies and moves of objects, and makes your code more flexible and efficient. However, it can also increase the complexity of your code and make debugging more difficult. Perfect forwarding uses forwarding references, which are special types of references that can bind to both lvalues and rvalues. The std::forward function is used to forward the argument to the appropriate version of the target function or template.</p><p><strong>Advantages</strong> of Perfect Forwarding:</p><ol><li><strong>Improved Performance:</strong> Perfect forwarding can improve performance by avoiding unnecessary copies and moves of objects.</li><li><strong>Flexibility</strong>: Perfect forwarding allows you to write more flexible and generic code by forwarding arguments to other functions or templates without losing their original types or qualifiers.</li><li><strong>Efficient Code Reuse:</strong> Perfect forwarding can allow you to write more efficient and reusable code by avoiding unnecessary duplication of functions or templates.</li></ol><p><strong><em>Disadvantages</em></strong> of Perfect Forwarding:</p><ol><li><strong>Complexity</strong>: Perfect forwarding can increase the complexity of your code, particularly if you’re not familiar with the technique. It can also make debugging more difficult.</li><li><strong>Compiler-specific Behavior:</strong> Perfect forwarding can behave differently across different compilers, which can make it harder to write portable code.</li><li><strong>Confusing Syntax:</strong> The syntax for perfect forwarding can be confusing and difficult to understand, particularly when dealing with rvalue references and forwarding references.</li></ol><p>Here’s an example implementation of perfect forwarding:</p><pre>#include &lt;iostream&gt;<br>#include &lt;utility&gt;<br><br>void foo(int&amp; x)<br>{<br>    std::cout &lt;&lt; &quot;lvalue reference: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br><br>void foo(int&amp;&amp; x)<br>{<br>    std::cout &lt;&lt; &quot;rvalue reference: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br><br>template&lt;typename T&gt;<br>void bar(T&amp;&amp; x)<br>{<br>    foo(std::forward&lt;T&gt;(x));<br>}<br><br>int main()<br>{<br>    int i = 42;<br><br>    bar(i); // lvalue reference<br>    bar(13); // rvalue reference<br><br>    return 0;<br>}</pre><p>In this example, we define two overloaded foo functions, one taking an lvalue reference and the other taking an rvalue reference. We also define a bar function that forwards its argument to foo using std::forward.</p><p>In the main function, we create an int variable i and call bar on i and on the integer literal 13. The bar function forwards the arguments to the appropriate version of foo using perfect forwarding.</p><p>Example Output:</p><pre>lvalue reference: 42<br>rvalue reference: 13</pre><p>As we can see from the output, the bar function correctly identifies the type of each argument and forwards them to the appropriate version of foo. The use of perfect forwarding in this example allows us to write generic code that works correctly with both lvalue and rvalue references.</p><blockquote>5-Type Traits</blockquote><p>Type traits are a powerful C++ template mechanism that provides information about the properties of a particular type at compile time. They are useful because they allow you to write more generic and flexible code that can adapt to different types without sacrificing performance.</p><p><strong><em>Advantages </em></strong>of Type Traits:</p><ol><li><strong>Compile-time Information:</strong> Type traits provide information about types at compile-time, which is more efficient than run-time checks.</li><li>Flexibility: Type traits allow you to write more generic and flexible code that can adapt to different types without sacrificing performance.</li><li><strong>Ease of Use</strong>: Type traits are easy to use and can be applied to any type.</li></ol><p><strong><em>Disadvantages </em></strong>of Type Traits:</p><ol><li><strong>Complexity</strong>: Type traits can be complex, especially for beginners. It may take some time to understand how to use them effectively.</li><li><strong>Compiler Errors: </strong>If the type trait is not defined correctly, it can result in difficult-to-understand compiler errors.</li></ol><p>Here is a full implemented example of type traits in C++:</p><pre>#include &lt;iostream&gt;<br><br>// Define a type trait to check if a type is a pointer<br>template&lt;typename T&gt;<br>struct is_pointer {<br>  static const bool value = false;<br>};<br><br>template&lt;typename T&gt;<br>struct is_pointer&lt;T*&gt; {<br>  static const bool value = true;<br>};<br><br>// Define a type trait to check if a type is an integer<br>template&lt;typename T&gt;<br>struct is_integer {<br>  static const bool value = false;<br>};<br><br>template&lt;&gt;<br>struct is_integer&lt;int&gt; {<br>  static const bool value = true;<br>};<br><br>template&lt;&gt;<br>struct is_integer&lt;long&gt; {<br>  static const bool value = true;<br>};<br><br>// Define a function template that checks the type of its argument<br>template&lt;typename T&gt;<br>void printTypeInfo(T value) {<br>  std::cout &lt;&lt; &quot;Type info: &quot;;<br>  if (is_pointer&lt;T&gt;::value) {<br>    std::cout &lt;&lt; &quot;pointer type&quot; &lt;&lt; std::endl;<br>  } else if (is_integer&lt;T&gt;::value) {<br>    std::cout &lt;&lt; &quot;integer type&quot; &lt;&lt; std::endl;<br>  } else {<br>    std::cout &lt;&lt; &quot;other type&quot; &lt;&lt; std::endl;<br>  }<br>}<br><br>int main() {<br>  int x = 1;<br>  float y = 3.14f;<br>  char* z = &quot;hello&quot;;<br><br>  printTypeInfo(x);<br>  printTypeInfo(y);<br>  printTypeInfo(z);<br>  <br>  return 0;<br>}</pre><p>Output:</p><pre>Type info: integer type<br>Type info: other type<br>Type info: pointer type</pre><p>In this example, we manually define two type traits: is_pointer and is_integer. The is_pointer type trait checks if a type is a pointer, while the is_integer type trait checks if a type is an integer.</p><p>We also define a function template called printTypeInfo that takes a value of any type and checks its type using the type traits. The output shows that the function correctly identifies the type of each variable.</p><blockquote>6-Pimpl(Pointer to Implementation)</blockquote><p>Pimpl (short for “Pointer to Implementation”) is a C++ programming idiom that allows a class’s implementation to be separated from its interface. Instead of defining all the implementation details of a class in the header file, Pimpl uses a pointer to a separate implementation class that is only defined in the implementation file.</p><p><strong><em>Advantages </em></strong>of Pimpl:</p><ol><li><strong>Reduces Compilation Time:</strong> Since the implementation details are hidden in a separate implementation class, changes made to the implementation don’t require recompiling the entire program.</li><li><strong>Hides Implementation Details:</strong> Clients of the class only need to include the header file and don’t need to know about the implementation details.</li><li><strong>Facilitates Binary Compatibility:</strong> Changing the implementation details of a class doesn’t affect the class’s binary interface, making it easier to maintain binary compatibility across different versions of the library.</li></ol><p><strong><em>Disadvantages </em></strong>of Type Traits:</p><ol><li><strong>Adds Indirection and Overhead:</strong> Since accessing members requires an extra indirection through a pointer, Pimpl can introduce some overhead compared to directly accessing members.</li><li><strong>Increases Complexity:</strong> Pimpl adds an extra layer of complexity to the code and can make debugging and maintenance more difficult.</li></ol><p>Here is an example implementation of Pimpl:</p><pre>// pimpl.h<br>class MyClass {<br> public:<br>  MyClass();<br>  ~MyClass();<br>  void doSomething();<br>  <br> private:<br>  class MyClassImpl;<br>  MyClassImpl* impl;<br>};</pre><pre>// pimpl.cpp<br>#include &quot;pimpl.h&quot;<br><br>class MyClass::MyClassImpl {<br> public:<br>  void doPrivateThing() {<br>    // implementation detail<br>  }<br>};<br><br>MyClass::MyClass() : impl(new MyClassImpl()) {}<br>MyClass::~MyClass() { delete impl; }<br><br>void MyClass::doSomething() {<br>  impl-&gt;doPrivateThing();<br>}</pre><p>In this example, the MyClassclass has a private pointer to a MyClassImpl class, which is only defined in the implementation file. Clients of the MyClass class only need to include the header file and don&#39;t need to know about the implementation details.</p><p>The MyClassImpl class contains the implementation details of the MyClass class, and clients of the MyClass class cannot access its members directly. Instead, clients can only access the MyClass class&#39;s public interface, which in turn calls the private members of the MyClassImpl class.</p><p>Here is an example usage of the MyClass class:</p><pre>// main.cpp<br>#include &quot;pimpl.h&quot;<br><br>int main() {<br>  MyClass myClass;<br>  myClass.doSomething();<br>  return 0;<br>}</pre><p>In this example, the main function creates a MyClass object and calls its doSomething function. Since the implementation details of doSomething are only defined in the implementation file, clients of the MyClass class don&#39;t need to know about them.</p><blockquote><strong>Conclusion</strong></blockquote><p>In conclusion, the 6 widely used C++ idioms (RAII, perfect forwarding, Pimpl, CRTP, SFINAE, and Type Traits) should be used to improve the quality and reliability of C++ code in various situations.</p><p>RAII can be used to manage resources automatically and avoid memory leaks, while perfect forwarding can be used to forward arguments to other functions without losing their types or references. Pimpl can be used to hide implementation details and increase binary compatibility, while CRTP can be used to add common functionality to a group of classes. SFINAE can be used to enable or disable function templates based on type traits, while type traits can be used to define types based on their properties.</p><p>Each idiom has its own advantages and disadvantages, and should be applied judiciously depending on the specific needs of the project. By understanding these idioms and using them appropriately, developers can write more efficient, safer, and flexible C++ code.</p><blockquote><strong>References</strong></blockquote><ul><li>Meyers, Scott. Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14. O’Reilly Media, Inc., 2014.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ab4792563e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Limitations of Named Return Value Optimization (NRVO) in C++ Compilers: Examples and…]]></title>
            <link>https://medium.com/@toramanbatur/exploring-the-limitations-of-named-return-value-optimization-nrvo-in-c-compilers-examples-and-b88b78fd1ae8?source=rss-63723746880f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88b78fd1ae8</guid>
            <category><![CDATA[return-value]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Batur Toraman]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 22:25:46 GMT</pubDate>
            <atom:updated>2023-02-28T22:42:29.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Limitations of Named Return Value Optimization (NRVO) in C++ Compilers: Examples and Outputs</h3><p>Named return value optimization (NRVO) is a compiler optimization technique that eliminates the unnecessary copying of objects returned from a function by reusing the same memory location that was used for the object inside the function. This optimization is only applicable in certain cases, and there are situations where the compiler cannot apply NRVO.</p><p>Here are some cases where NRVO may not be applicable by the compiler:</p><ul><li>Multiple return statements: If a function has multiple return statements that return different objects, then NRVO cannot be applied as there are multiple objects that need to be constructed and returned.</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>class Person {<br>public:<br>    Person(const std::string&amp; name) : name_(name) {<br>        std::cout &lt;&lt; &quot;Constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    Person(const Person&amp; other) : name_(other.name_) {<br>        std::cout &lt;&lt; &quot;Copy-constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    ~Person() {<br>        std::cout &lt;&lt; &quot;Destructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    std::string getName() const {<br>        return name_;<br>    }<br><br>private:<br>    std::string name_;<br>};<br><br>Person getPerson(bool isMale) {<br>    if (isMale) {<br>        Person malePerson(&quot;John&quot;);<br>        return malePerson;<br>    } else {<br>        Person femalePerson(&quot;Jane&quot;);<br>        return femalePerson;<br>    }<br>}<br><br>int main() {<br>    std::cout &lt;&lt; &quot;Calling getPerson(true)&quot; &lt;&lt; std::endl;<br>    Person male = getPerson(true);<br><br>    std::cout &lt;&lt; &quot;Calling getPerson(false)&quot; &lt;&lt; std::endl;<br>    Person female = getPerson(false);<br><br>    std::cout &lt;&lt; &quot;End of main&quot; &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><pre>Calling getPerson(true)<br>Constructing Person John<br>Copy-constructing Person John<br>Destructing Person John<br>Calling getPerson(false)<br>Constructing Person Jane<br>Copy-constructing Person Jane<br>Destructing Person Jane<br>End of main<br>Destructing Person Jane<br>Destructing Person John</pre><ul><li>Conditional return statements: If a function has a conditional return statement, where the object returned depends on a condition, then NRVO may not be applied as the compiler cannot determine which object should be returned before the function is executed.</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>class Person {<br>public:<br>    Person(const std::string&amp; name) : name_(name) {<br>        std::cout &lt;&lt; &quot;Constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    Person(const Person&amp; other) : name_(other.name_) {<br>        std::cout &lt;&lt; &quot;Copy-constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    ~Person() {<br>        std::cout &lt;&lt; &quot;Destructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    std::string getName() const {<br>        return name_;<br>    }<br><br>private:<br>    std::string name_;<br>};<br><br>Person getPerson(bool isMale) {<br>    Person person(&quot;&quot;);<br>    if (isMale) {<br>        person = Person(&quot;John&quot;);<br>    }<br>    else {<br>        person = Person(&quot;Jane&quot;);<br>    }<br>    return person;<br>}<br><br><br>int main() {<br>    std::cout &lt;&lt; &quot;Calling getPerson(true)&quot; &lt;&lt; std::endl;<br>    Person male = getPerson(true);<br><br>    std::cout &lt;&lt; &quot;Calling getPerson(false)&quot; &lt;&lt; std::endl;<br>    Person female = getPerson(false);<br><br>    std::cout &lt;&lt; &quot;End of main&quot; &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><pre>Calling getPerson(true)<br>Constructing Person<br>Constructing Person John<br>Destructing Person John<br>Copy-constructing Person John<br>Destructing Person John<br>Calling getPerson(false)<br>Constructing Person<br>Constructing Person Jane<br>Destructing Person Jane<br>Copy-constructing Person Jane<br>Destructing Person Jane<br>End of main<br>Destructing Person Jane<br>Destructing Person John</pre><ul><li>Functions with side effects: If a function has side effects, such as modifying global variables or calling other functions that modify global variables, then NRVO may not be applied as the compiler cannot guarantee that the returned object is the same as the one constructed inside the function.</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>int count = 0;<br><br>class Person {<br>public:<br>    Person(const std::string&amp; name) : name_(name) {<br>        std::cout &lt;&lt; &quot;Constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    Person(const Person&amp; other) : name_(other.name_) {<br>        std::cout &lt;&lt; &quot;Copy-constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    ~Person() {<br>        std::cout &lt;&lt; &quot;Destructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    std::string getName() const {<br>        return name_;<br>    }<br><br>private:<br>    std::string name_;<br>};<br><br>Person getPerson() {<br>    Person person(&quot;John&quot;);<br>    count++;<br>    return person;<br>}<br><br>int main() {<br>    std::cout &lt;&lt; &quot;Calling getPerson()&quot; &lt;&lt; std::endl;<br>    Person person = getPerson();<br><br>    std::cout &lt;&lt; &quot;End of main, count = &quot; &lt;&lt; count &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><pre>Calling getPerson()<br>Constructing Person John<br>Copy-constructing Person John<br>Destructing Person John<br>End of main, count = 1<br>Destructing Person John</pre><ul><li>The recommended approach to resolving this problem would entail producing a solution that closely aligns with the following specifications</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>class Person {<br>public:<br>    Person(const std::string&amp; name) : name_(name) {<br>        std::cout &lt;&lt; &quot;Constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    Person(const Person&amp; other) : name_(other.name_) {<br>        std::cout &lt;&lt; &quot;Copy-constructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    ~Person() {<br>        std::cout &lt;&lt; &quot;Destructing Person &quot; &lt;&lt; name_ &lt;&lt; std::endl;<br>    }<br><br>    std::string getName() const {<br>        return name_;<br>    }<br><br>private:<br>    std::string name_;<br>};<br><br>Person getFemale() <br>{<br>    return Person(&quot;Jane&quot;);<br>}<br>Person getMale()<br>{<br>    return Person(&quot;John&quot;);<br>}<br><br>int main() {<br>    std::cout &lt;&lt; &quot;Calling getMale&quot; &lt;&lt; std::endl;<br>    Person male = getMale();<br><br>    std::cout &lt;&lt; &quot;Calling getFemale&quot; &lt;&lt; std::endl;<br>    Person female = getFemale();<br><br>    std::cout &lt;&lt; &quot;End of main&quot; &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><pre>Calling getMale<br>Constructing Person John<br>Calling getFemale<br>Constructing Person Jane<br>End of main<br>Destructing Person Jane<br>Destructing Person John</pre><ul><li>Different types: If the return value is a different type than the object being constructed, the compiler may not be able to apply NRVO.</li></ul><p><strong><em>Conclusion</em></strong></p><p>Named Return Value Optimization (NRVO) is an important optimization technique in C++ that can significantly improve code performance. However, its applicability is dependent on the compiler and there are certain limitations that developers should be aware of. Specifically, NRVO cannot be applied when the return value is a different type than the object being constructed or when there are multiple return statements in the function. By understanding these limitations, developers can write more efficient and reliable code that takes full advantage of the performance benefits offered by NRVO.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88b78fd1ae8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Eliminating Cyclic Dependency in C++: Solving Object Destruction Issues with Weak Pointers”]]></title>
            <link>https://medium.com/@toramanbatur/eliminating-cyclic-dependency-in-c-solving-object-destruction-issues-with-weak-pointers-6bc495ebdae6?source=rss-63723746880f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bc495ebdae6</guid>
            <dc:creator><![CDATA[Batur Toraman]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 14:59:03 GMT</pubDate>
            <atom:updated>2023-02-17T15:10:07.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*bH0GxfeTUE0CwJqkajmijA.png" /></figure><p>In object-oriented programming, a cyclic dependency occurs when two or more classes depend on each other in a circular manner. This is a common problem in C++ programming when two classes, A and B, have each other’s instance as a member shared pointer. This creates a cyclic dependency, where the ownership of objects is not well-defined, and can lead to memory leaks or undefined behavior. As a C++ programmer, I know firsthand the struggles of dealing with cyclic dependency issues. That’s why I wrote a new Medium essay sharing my insights and solutions for avoiding object destruction problems using weak pointers. If you’re a fellow C++ programmer looking for some helpful tips, I invite you to check it out!</p><h4>The Problem with Cyclic Dependency</h4><p>When two classes, A and B, hold a shared pointer to each other, it creates a cyclic dependency, as both classes depend on each other. This can lead to problems when objects are destructed, as the order of destruction is not well-defined. When a shared pointer is destroyed, it checks if there are any other shared pointers that are referencing the same object. If there are no other shared pointers, then the object is destructed. However, in a cyclic dependency, both objects hold a shared pointer to each other, which creates a problem when trying to destruct them.</p><pre>class A {<br>public:<br>    std::shared_ptr&lt;B&gt; b;<br>};<br><br>class B {<br>public:<br>    std::shared_ptr&lt;A&gt; a;<br>};</pre><h4>Solving the Problem with Weak Pointers</h4><p>To solve the cyclic dependency problem, one of the shared pointers must be replaced with a weak pointer. A weak pointer is a type of smart pointer that allows you to hold a non-owning reference to an object that is owned by a shared pointer. The object will only be destructed when all the shared pointers that reference it are destructed.</p><pre>class A {<br>public:<br>    std::weak_ptr&lt;B&gt; b;<br>};<br><br>class B {<br>public:<br>    std::shared_ptr&lt;A&gt; a;<br>};</pre><p>Here, class A holds a weak pointer to class B, and class B holds a shared pointer to class A. This eliminates the cyclic dependency, as the objects will be properly destructed when all the shared pointers that reference them are destructed. The weak pointer in class A will not increase the reference count, and hence will not prevent the object’s destruction, even if there are still shared pointers in class B.</p><h4>Conclusion</h4><p>Cyclic dependency is a common problem in object-oriented programming. When two classes have each other’s instance as a member shared pointer, it can lead to problems in object destruction. One way to solve this problem is by making one of them a weak pointer. By doing so, we can eliminate the cyclic dependency and ensure that objects are destructed properly. The weak pointer will not increase the reference count, and hence will not prevent the object’s destruction, even if there are still shared pointers in the other class. In this way, we can avoid memory leaks and undefined behavior in our code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc495ebdae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>