<?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 Baycan Vural on Medium]]></title>
        <description><![CDATA[Stories by Baycan Vural on Medium]]></description>
        <link>https://medium.com/@baycan.vural?source=rss-dd96bdc3e1f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hgYjF0MJg-grXdEvMD0b0A.jpeg</url>
            <title>Stories by Baycan Vural on Medium</title>
            <link>https://medium.com/@baycan.vural?source=rss-dd96bdc3e1f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:04:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baycan.vural/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[C++ Diaries: GitLab, One tool to rule them all]]></title>
            <link>https://medium.com/@baycan.vural/c-diaries-gitlab-one-tool-to-rule-them-all-0bd9f831d393?source=rss-dd96bdc3e1f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bd9f831d393</guid>
            <dc:creator><![CDATA[Baycan Vural]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 11:09:32 GMT</pubDate>
            <atom:updated>2025-06-11T11:09:32.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESuPclk4MGnTfDGrZmlZcg.jpeg" /></figure><p>As a senior software engineer, your role extends beyond pure coding. You must grasp architectural patterns and the Software Development Life Cycle (SDLC). These concepts are inevitable companions in your career journey, and familiarity with them is essential. At minimum, you should possess a solid understanding of their fundamentals. In my earlier <a href="https://www.linkedin.com/pulse/exploring-lifetime-software-different-perspective-baycan-vural-5zhpf/?trackingId=jKVO09yP16aGlkW7W2kfoQ%3D%3D">writing</a>, I explored the significance of architecture and its impact on project longevity in this piece. Now, let’s delve into SDLC.</p><p>SDLC represents a universal framework that typically encompasses these phases:<br>- Build<br>- Verify <br>- Secure<br>- Package<br>- License Check<br>- Deploy</p><p>Quite an extensive list of steps to execute properly, isn’t it? Picture handling each of these phases manually — I can sense your frustration already. This challenge is precisely what the DevOps/DevSecOps field addresses: identifying these processes and determining optimal automation strategies to liberate us from this tedious burden. Proper DevOps structure is important to have. Specially if for a C++ developer it is must. It must be the first thing you have to establish for your project even before gathering requirements.</p><p>Furthermore, SDLC includes preliminary phases such as requirements gathering, documentation creation, planning, and project management — the list of potential steps continues to expand. Traditionally, we rely on various specialized tools for each phase: documentation platforms like Confluence, task and project management systems like Jira, automation tools like Jenkins, and version control systems like Git for development work. The pattern persists endlessly. This creates another challenge — mastering numerous distinct tools and their respective interfaces. However, here’s the encouraging news: this fragmentation is exactly what GitLab aims to resolve. It offers a singular platform with one unified interface to master, addressing all our development needs. Truly, one tool to rule them all!</p><p>GitLab can be explored through two primary approaches: utilizing the Software-as-a-Service (SaaS) offering provided by GitLab Inc., or deploying your own self-hosted GitLab installation. For comprehensive understanding and complete administrative control over GitLab’s functionality, I recommend setting up your personal GitLab instance. While a brief article cannot cover every intricate detail, I will guide you through the process of establishing your own instance to get you started effortlessly.</p><p><strong>Prerequisite</strong></p><ul><li>A machine installed vagrant and virtualbox plugins.</li></ul><p><strong>Preparing Vagrantfile</strong></p><p>Simplest vagrantfile showed below. You may choose different box and configuration as well. The most important config here that we creates a bridge to able to give a public ip (<strong>192.168.1.20</strong>) for our box. Of course this ip must not be used for other local area host machines and you have to be aware of network mask. Probably you have to choose a proper ip depending on your local network. Also you have to spare cpu and memory for the virtual machine that you will run your self hosted GitLab. It is better to spare recommended resources for the instance to don’t face any performance issues.</p><pre># -*- mode: ruby -*-<br># vi: set ft=ruby :<br><br>Vagrant.configure(&quot;2&quot;) do |config|<br><br>  config.vm.box = &quot;debian/bookworm64&quot;<br>  config.vm.box_version = &quot;12.20250126.1&quot;<br><br>  # NOTE: This will enable public access to the opened port<br>  config.vm.network &quot;public_network&quot;, ip: &quot;192.168.1.20&quot;<br><br>  config.vm.synced_folder &quot;./&quot;, &quot;/vagrant_data&quot;<br><br>  config.vm.provider &quot;virtualbox&quot; do |vb|<br>     vb.cpus = &quot;4&quot;<br>     vb.memory = &quot;8192&quot;<br>   end<br><br>   config.vm.provision &quot;shell&quot;, inline: &lt;&lt;-SHELL<br>     apt-get update<br>   SHELL<br>end</pre><p>Save this vagrantfile in a directory and run this command inside of that directory to bring up vagrant box</p><pre>$ vagrant up</pre><p>Probably it will ask you to choose the interface that you would like to bridged. Like it is recommended choose the one that you use to connect internet. In my case I have chosen <em>1</em> like showed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfNhNXdV68IX7RjF-_7feQ.png" /></figure><p>After machine booted and ready I suggest you to check that you can ping to just booted machine with given ip. In my case it was <strong>192.168.1.20</strong>. thats how we can be sure that we can reach booted machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*Eyw7gSgrHfXiaSN0tEiusA.png" /></figure><p>If you can ping the machine now we can get into the guest machine and start installing GitLab. To able to switch to guest machine we can just use this command into same directory:</p><pre>$ vagrant ssh</pre><p>Now it’s time to install GitLab. Following GitLab’s official recommendations, we’ll install the Enterprise Edition. No payment is required unless you need access to premium features. I assure you that the free version will suffice for most use cases. GitLab provides distribution repositories that enable installation through native package management systems. We’ll download and execute a ready-made script provided by GitLab, making the process seamless.</p><p>During installation, I specified the EXTERNAL_URL=”<a href="https://gitlab.baycan.com/">https://gitlab.baycan.com</a>&quot; variable to define the domain name for my GitLab instance. You can choose any domain name you prefer. After executing this command, GitLab configuration will begin immediately.</p><pre>$ sudo apt-get install -y curl openssh-server ca-certificates perl<br>$ curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh | sudo bash<br>$ sudo EXTERNAL_URL=&quot;https://gitlab.baycan.com&quot; apt-get install gitlab-ee</pre><p><strong>Important</strong></p><p>After the final command completes, you’ll likely encounter a certificate error since gitlab.baycan.com isn’t a recognized domain name — we created it for demonstration purposes. If you have your own DNS server, you can add this domain name to resolve the issue. Alternatively, you can use http:// without SSL security. I recommend ignoring this error for now and verifying that GitLab services are running properly using the command shown below. If everything is functioning correctly, you should see output similar to mine. Don’t forget to capture your root password! When GitLab is first installed, it automatically generates a password for the root user. You should change this password immediately upon first login. You can find this root password in the `/etc/gitlab/initial_root_password` file.</p><pre>$ sudo gitlab-ctl status<br><br>run: crond: (pid 19147) 3293s; run: log: (pid 19160) 3290s<br>run: gitaly: (pid 19508) 3203s; run: log: (pid 18866) 3405s<br>run: gitlab-kas: (pid 19081) 3394s; run: log: (pid 19093) 3393s<br>run: gitlab-workhorse: (pid 19496) 3204s; run: log: (pid 19232) 3274s<br>run: logrotate: (pid 18774) 3420s; run: log: (pid 18783) 3417s<br>run: nginx: (pid 19519) 3203s; run: log: (pid 19255) 3271s<br>run: postgresql: (pid 18908) 3401s; run: log: (pid 18925) 3398s<br>run: puma: (pid 19163) 3287s; run: log: (pid 19170) 3286s<br>run: redis: (pid 18810) 3414s; run: log: (pid 18819) 3413s<br>run: registry: (pid 19527) 3203s; run: log: (pid 19364) 3244s<br>run: sidekiq: (pid 19179) 3281s; run: log: (pid 19202) 3278s</pre><p><strong>Accessing Your GitLab Instance</strong></p><p>Our GitLab server is now ready and running on the guest machine. We can return to the host machine and attempt to access our GitLab domain (gitlab.baycan.com) through a web browser. However, since no one recognizes where gitlab.baycan.com is located, we need to address this. If you don’t have your own DNS server, don’t worry — we can manually add this server address to our host machine. To do this manually, append the following entry to the end of your `/etc/hosts` file:</p><pre>192.168.1.20 gitlab.baycan.com</pre><p>After editing the `/etc/hosts` file, you can test it in your browser using <a href="https://gitlab.baycan.com/">https://gitlab.baycan.com/</a> in my case. You should see the login screen. Enter the password for the root user that you retrieved from the `/etc/gitlab/initial_root_password` file. You should now see your admin dashboard on your self-hosted GitLab instance. At this point, you can feel like “alright, alright, alright!” :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Smdh9pNu4JvMD1aUr3CJOA.gif" /></figure><p><strong>Next Steps and Learning Opportunities</strong></p><p>Now that we have a functional self-hosted GitLab instance, what comes next? I recommend treating this instance as your personal learning environment. Begin exploring how GitLab manages various aspects of development. How do you write requirements? How do you create documentation and wiki pages? How do you establish tasks and boards, and how do you manage them? Try to understand GitLab’s Group, Subgroup, and Project hierarchy. Experiment with creating your own projects, making commits, and submitting merge requests. One of GitLab’s most powerful features is its CI/CD Pipeline capabilities. Take time to understand the components of GitLab Runner — what it does and how it operates. You can even install your first GitLab Runner using the exact same Vagrantfile provided above. Installing and registering a GitLab Runner is thoroughly documented in GitLab’s official documentation. Additionally, explore the package registry and container image registry features — learn how to leverage these powerful tools. GitLab is a vast ecosystem with countless features to discover, far more than I could cover in a single article. This piece was designed to provide you with a solid starting point. As I mentioned, this is your playground — experiment, break things, and rebuild them. You’re operating in a completely isolated environment thanks to virtualization.</p><p>I hope you found this article enjoyable and informative. I look forward to receiving your feedback and comments.</p><p><strong>References</strong></p><ul><li>GitLab official documentation (<a href="https://docs.gitlab.com/">https://docs.gitlab.com/</a>)</li><li>Automating DevOps with GitLab CI/CD Pipelines: Build efficient CI/CD pipelines to verify, secure, and deploy your code using real-life examples — by Christopher Cowell, Nicholas Lotz, Chris Timberlake</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bd9f831d393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Diaries: Navigating Pointer Interoperability in Modern C++]]></title>
            <link>https://medium.com/@baycan.vural/c-diaries-navigating-pointer-interoperability-in-modern-c-3cd46738f594?source=rss-dd96bdc3e1f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cd46738f594</guid>
            <dc:creator><![CDATA[Baycan Vural]]></dc:creator>
            <pubDate>Mon, 19 May 2025 08:11:21 GMT</pubDate>
            <atom:updated>2025-05-19T08:11:21.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESuPclk4MGnTfDGrZmlZcg.jpeg" /></figure><p>Modern C++ is truly impressive, and with each new standard, it continues to improve — there’s no doubt about that. We’re seeing the addition of expressive language features, better control over ownership, enhanced value semantics, improved type safety, and more security-focused capabilities.</p><p>However, these benefits are most apparent when we write C++ in a clean, isolated environment without interacting with legacy code or third-party libraries. The moment we step outside this controlled space — especially when integrating with C libraries or older C++ code bases — things can quickly become messy.</p><p>Consider what happens when you use a C library: you’re immediately dealing with raw pointers. And we all know that raw pointers are inherently unsafe and error-prone. Naturally, we want to avoid them. Thankfully, the C++ standards committee anticipated this and provided features to help with interoperability.</p><p><strong>Scenario 1</strong></p><p>Let’s examine a basic example shown below. Suppose we’re using a C library that requires us to initialize an API, which returns a raw pointer — Foo* in our case. According to the API contract, we must explicitly call foo_clean to release the resources associated with each Foo* instance.</p><pre>// foo.h<br> <br>struct Foo;<br><br>Foo* foo_init();<br>void foo_clean(Foo* object);</pre><p>This means that even in modern C++, we’re forced to deal with raw Foo* pointers. Does that align with modern C++ best practices? Absolutely not. In a complex codebase, relying on manual cleanup increases the risk of resource leaks. Ownership is a critical concept in modern C++, and failing to manage it correctly can easily lead to memory leaks or other bugs.</p><p>To ensure proper interoperability between C++ smart pointers and raw C pointers, we need to integrate them carefully. Below, I’ve outlined a few solutions to handle this. By wrapping the raw resource in a modern C++ smart pointer with a custom deleter, we eliminate the risk of forgetting to call foo_clean(). Once the smart pointer goes out of scope, the custom deleter ensures that foo_clean() is automatically invoked, providing safe and reliable resource management.</p><pre>// first solution.<br>auto smartFoo2 = std::unique_ptr&lt;Foo, decltype(&amp;foo_clean)&gt; { foo_init(), foo_clean };</pre><p>We can achieve the same result by defining a functor struct or using a lambda function — both of which can serve as custom deleters.</p><pre>// Second solution<br>struct FooDeleter {<br>    void operator()(Foo* object){<br>        foo_clean(object);<br>    }<br>};<br><br>auto smartFoo = std::unique_ptr&lt;Foo, FooDeleter&gt; { foo_init() };</pre><p><a href="https://godbolt.org/z/o66nKPPE8">Here</a> is a full compiler explorer code.</p><p><strong>Scenario 2</strong></p><p>Another common pattern in C-style APIs involves the use of output parameters. These functions typically return an error code, while any resource allocation is performed through pointer arguments passed by reference. Below is a simple example illustrating this approach.</p><pre>int bar_alloc(int value, int** data);<br>void bar_free(int* data); </pre><p>Here, bar_alloc() returns a status code and provides the allocated resource via an output parameter.</p><p>We can still use std::unique_ptr to manage the resource, pairing it with a custom deleter</p><pre>std::unique_ptr&lt;int, decltype(&amp;bar_free)&gt; smartData(nullptr, bar_free);<br>bar_alloc(42, std::inout_ptr(smartData));</pre><p>In this example, std::inout_ptr() serves as a convenient bridge between std::unique_ptr and C-style output parameters. If we can guarantee that the smart pointer is initially set to nullptr, we can alternatively use std::out_ptr() instead.</p><p>In the examples above, I used std::unique_ptr, but you can apply the same approach using std::shared_ptr if shared ownership semantics are required.</p><p><a href="https://godbolt.org/z/c7xhv3Pvc">Here</a> is a full compiler explorer code.</p><p>Please, feel free to share your thoughts on this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cd46738f594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Diaries: Meyers’ Singleton Class Implementation]]></title>
            <link>https://medium.com/@baycan.vural/c-diaries-meyers-singleton-class-implementation-7548bb76b3ed?source=rss-dd96bdc3e1f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7548bb76b3ed</guid>
            <dc:creator><![CDATA[Baycan Vural]]></dc:creator>
            <pubDate>Thu, 08 May 2025 21:38:13 GMT</pubDate>
            <atom:updated>2025-05-08T21:38:13.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESuPclk4MGnTfDGrZmlZcg.jpeg" /></figure><p>The Singleton design pattern is among the most commonly used in software development. Despite its popularity, it often sparks debate — critics argue that it introduces tight coupling and complicates tasks like unit testing or extending functionality. While I recognize these concerns, I also believe that no programming technique is inherently “bad.” In certain scenarios, the Singleton pattern can greatly simplify development. That’s why it remains relevant, and it’s important to understand both what it is and how to implement it effectively.</p><p>There are several ways to implement the Singleton pattern. In this article, I’ll walk you through two different approaches. We’ll compare them and ultimately determine which one is the better option. Let’s start with the less ideal implementation.</p><p><strong>The “Bad” Singleton</strong></p><p>I refer to this version as “bad” because it involves direct pointer manipulation and more critically, it is not thread-safe in a multi-threaded environment. To ensure safe usage, additional synchronization mechanisms are required. To detect potential race conditions, we can use GCC sanitizers — specifically, the Thread Sanitizer. If you compile and run the code below with the sanitizer enabled, you’ll likely see a large output highlighting the presence of race conditions.</p><pre>// bad_singleton.cpp<br><br>// compile($): g++ -std=c++23 --sanitize=thread bad_singleton.cpp -o bad_singleton<br>// run($): ./bad_singleton<br><br>#include &lt;memory&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br><br>class BadSingleton {<br>public:<br>    static BadSingleton&amp; instance() {<br>        if (!single) {<br>            single.reset(new BadSingleton);<br>        }<br><br>        return *single;<br>    }<br>    void doSomething() {}<br><br>private:<br>    BadSingleton() = default;<br>    BadSingleton(const BadSingleton&amp;) = delete;<br>    BadSingleton(BadSingleton&amp;&amp;) = delete;<br>    BadSingleton&amp; operator=(BadSingleton&amp;&amp;) = delete;<br>    BadSingleton&amp; operator=(const BadSingleton&amp;) = delete;<br><br>    static inline std::unique_ptr&lt;BadSingleton&gt; single;<br>};<br><br>int main() {<br>    std::vector&lt;std::jthread&gt; threads;<br>    <br>    constexpr auto ThreadNumber = 2U;<br>    for (auto i = 0U; i &lt; ThreadNumber; i++)<br>    {<br>        threads.push_back(std::jthread{[]{<br>            auto&amp; badInstance = BadSingleton::instance();<br>            badInstance.doSomething();<br>        }});<br>     }<br><br>    return 0;<br>}</pre><p><strong>Meyers’ Singleton</strong></p><p>In contrast, Meyers’ Singleton is a much better alternative. It relies on a function-local static variable to ensure that the Singleton instance is created only once. This approach is thread-safe by default, thanks to guarantees in the C++11 standard and later. According to the standard, static local variables are initialized in a thread-safe manner, making this implementation safe and efficient without the need for additional synchronization.</p><pre>// meyers_singleton.cpp<br><br>// compile($): g++ -std=c++23 --sanitize=thread meyers_singleton.cpp -o meyers_singleton<br>// run($): ./meyers_singleton<br><br>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br><br>class MeyersSingleton {<br>    public:<br><br>    static MeyersSingleton&amp; instance() {<br>        static MeyersSingleton single;<br>        return single;<br>    }<br><br>    void doSomething(){}<br><br>    private:<br>    MeyersSingleton() = default;<br>    MeyersSingleton(const MeyersSingleton&amp;) = delete;<br>    MeyersSingleton(MeyersSingleton&amp;&amp;) = delete;<br>    MeyersSingleton&amp; operator=(MeyersSingleton&amp;&amp;) = delete;<br>    MeyersSingleton&amp; operator=(const MeyersSingleton&amp;) = delete;<br>};<br><br>int main() {<br>    std::vector&lt;std::jthread&gt; threads;<br><br>    constexpr auto ThreadNumber = 2U;<br>    for (auto i = 0U; i &lt; ThreadNumber; i++)<br>    {<br>        threads.push_back(std::jthread{[]{<br>            auto&amp; instance = MeyersSingleton::instance();<br>            instance.doSomething();<br>        }});<br>    }<br><br>    return 0;<br>}</pre><p><strong>References</strong></p><ul><li>Effective C++ — Scott Meyer</li><li>C++ Software Design — Design Principles and Patterns for High-Quality Software by Klaus Iglberger</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7548bb76b3ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Diaries: Zero overhead, full flavor — std::string_view]]></title>
            <link>https://medium.com/@baycan.vural/c-diaries-zero-overhead-full-flavor-std-string-view-9340855c7476?source=rss-dd96bdc3e1f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9340855c7476</guid>
            <dc:creator><![CDATA[Baycan Vural]]></dc:creator>
            <pubDate>Tue, 06 May 2025 15:19:06 GMT</pubDate>
            <atom:updated>2025-05-06T15:19:06.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>C++ Diaries: Zero overhead, full flavor — std::string_view</h3><p>Strings have been a notorious source of trouble in the embedded domain for a long time, especially when programming in C or C++. One of the challenges is carefully handling the null-terminating (NUL) character. There’s also frequent confusion between NUL (the character that ends a string) and NULL, the constant that represents a null pointer. They are actually different concepts. But if you don’t believe me, feel free to check the ASCII table yourself!</p><p>In C++, std::string has never been a true “first-class” type. It’s simply an alias for the std::basic_string template class. However, the C++ committee has continually worked on improving the type, introducing optimizations like Small String Optimization (SSO).</p><p>One of the other most significant improvements came with C++17: the introduction of std::string_view. By now, you may have heard that it’s better to use std::string_view over const std::string&amp;. As reasonable developers, we naturally ask: why? There’s always a reason for the existence of such features.</p><p>So, why would I need std::string_view if I already have const std::string&amp; ? One of the key reasons can be demonstrated in this example:</p><pre>#include &lt;print&gt;<br>#include &lt;string&gt;<br><br>void printMe(const std::string&amp; message) {<br>  std::println(&quot;{}&quot;, message);<br>}<br><br>int main() {<br>  printMe(&quot;hello world&quot;);<br><br>  return 0;<br>}</pre><p>Now, let’s take a moment to think about what’s happening here. The <em>printMe</em> function accepts a <em>const std::string&amp; </em>argument. We’re passing a string literal, “hello world”, to this function. However, “hello world” is not a std::string — it’s a string literal, which the compiler interprets as a <em>const char*</em>. Since this isn’t a std::string, the compiler implicitly creates a temporary std::string object to pass to the <em>printMe</em> function.</p><p>For small strings, this implicit conversion might not seem like a big deal, thanks to SSO (Small String Optimization). But for larger string literals, this operation results in a dynamic allocation on the heap — something we all know can be expensive. This is where std::string_view shines. Its primary purpose is to avoid these unnecessary copies and temporary std::string objects. With std::string_view, you get all the benefits of performance: it never copies, and it never creates an implicit std::string. It’s all about efficiency.</p><pre>#include &lt;print&gt;<br>#include &lt;string&gt;<br>#include &lt;string_view&gt;<br><br>void printMe(const std::string_view message) {<br>    std::println(&quot;{}&quot;, message);<br>}<br><br>int main() {<br><br>    printMe(&quot;hello world&quot;);<br>    return 0;<br>}</pre><h3>std::string_view as return type</h3><p>But what about using std::string_view as a return type? It might seem like a great idea at first, but there are some critical pitfalls to watch out for.</p><p>Let’s break it down. You can return std::string_view from a function, but the real question is: should you? And the answer depends on the type you’re returning.</p><p>If your function returns a std::string that isn’t const and could be modified, using std::string_view as the return type is risky. Here’s why: std::string is a dynamically allocated array. When the string mutates, it can reallocate, changing its underlying memory address and freeing the old memory location. If we return std::string_view (which is essentially a pointer to the beginning of the string and a size), we might be pointing to memory that’s already been released. This leads to a dangling std::string_view, which can cause undefined behavior or even crash your program</p><pre>#include &lt;print&gt;<br>#include &lt;string&gt;<br>#include &lt;string_view&gt;<br><br>struct Temp {<br>  std::string_view returnMe() {<br>    return m_message;<br>  }<br><br>  void setMessage(std::string_view message) {<br>    m_message = message;<br>  }<br><br>  std::string m_message;<br>};<br><br>int main() {<br><br>  auto tempObj = Temp{};<br>  auto tempMessage = tempObj.returnMe();<br>  return 0;<br>}</pre><p>To safely use std::string_view as a return type, ensure it points to a constant, non-temporary string. Common safe uses include returning views of const std::string objects, string literals, or other immutable strings.</p><p>Avoiding dangling std::string_view pointers will save you from potential headaches and keep your code robust and reliable.</p><pre>#include &lt;print&gt;<br>#include &lt;string&gt;<br>#include &lt;string_view&gt;<br><br>struct Temp {<br>  std::string_view returnMe() {<br>    return &quot;I am a string literal&quot;;<br>  }<br><br>};<br><br>int main() {<br><br>  auto tempObj = Temp{};<br>  auto tempMessage = tempObj.returnMe();<br>  return 0;<br>}</pre><p>Please feel free to share your thoughts about the topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9340855c7476" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>