<?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 W on Medium]]></title>
        <description><![CDATA[Stories by W on Medium]]></description>
        <link>https://medium.com/@mfnqxfb?source=rss-98e19a3a8100------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by W on Medium</title>
            <link>https://medium.com/@mfnqxfb?source=rss-98e19a3a8100------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:23:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mfnqxfb/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++ 11]]></title>
            <link>https://medium.com/@mfnqxfb/c-11-35516e2624d5?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/35516e2624d5</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:43:12 GMT</pubDate>
            <atom:updated>2026-10-24T04:43:12.434Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>struct Gadget {<br> Gadget(Gadget&amp;&amp;)=default;<br> Gadget(const Gadget&amp;)=default; <br>}; <br>const Gadget g=build(); <br>Gadget h = std::move(g);<br> Which constructor initializes h?</blockquote><blockquote>Answer: The copy constructor: std::move(g) has type const Gadget&amp;&amp;, which cannot bind to Gadget&amp;&amp;, so it binds to const Gadget&amp; instead.</blockquote><p>The key idea here is easy to miss: <strong>std::move() doesn’t remove </strong><strong>const</strong>. It changes the value category to an rvalue/xvalue, but the object stays const.</p><p>Given:</p><pre>struct Gadget {<br>    Gadget(Gadget&amp;&amp;) = default;<br>    Gadget(const Gadget&amp;) = default;<br>};<br>const Gadget g = build();<br>Gadget h = std::move(g);</pre><p>h is initialized using the <strong>copy constructor</strong>:</p><pre>Gadget(const Gadget&amp;);</pre><h3>1. What does std::move(g) actually produce?</h3><p>You can think of std::move(g) roughly as a cast:</p><pre>static_cast&lt;const Gadget&amp;&amp;&gt;(g</pre><p>Since g is:</p><pre>const Gadget</pre><p>std::move(g) produces an xvalue whose type is:</p><pre>const Gadget&amp;&amp;</pre><p>So the transformation is:</p><pre>g<br>type: const Gadget<br>category: lvalue<br>        │<br>        │ std::move<br>        ▼<br>std::move(g)<br>type: const Gadget<br>category: xvalue</pre><p>This is why the name std::move can be slightly misleading. It doesn&#39;t perform a move itself; it says, essentially, <strong>“treat this expression as an rvalue.”</strong></p><h3>2. Why can’t the move constructor take it?</h3><p>Your move constructor is:</p><pre>Gadget(Gadget&amp;&amp;);</pre><p>It wants a non-const rvalue reference:</p><pre>Gadget&amp;&amp;</pre><p>But you’re giving it:</p><pre>const Gadget&amp;&amp;</pre><p>That can’t bind to Gadget&amp;&amp;, because doing so would discard const:</p><pre>const Gadget&amp;&amp;<br>      ↓<br>   Gadget&amp;&amp;       ❌ would discard const</pre><p>There’s a good practical reason for this rule. Moving normally modifies the source object.</p><p>For example, imagine Gadget owns some memory:</p><pre>class Gadget {<br>    int* ptr;<br>public:<br>    Gadget(Gadget&amp;&amp; other)<br>        : ptr(other.ptr)<br>    {<br>        other.ptr = nullptr;<br>    }<br>};</pre><p>The move constructor steals the pointer and then changes the source:</p><pre>other.ptr = nullptr;</pre><p>If other were const, that modification wouldn&#39;t be allowed. That&#39;s why move constructors normally accept:</p><pre>T&amp;&amp;</pre><p>rather than:</p><pre>const T&amp;&amp;</pre><h3>3. Why does the copy constructor work?</h3><p>The copy constructor takes:</p><pre>Gadget(const Gadget&amp;);</pre><p>A const Gadget&amp; can bind to a const Gadget&amp;&amp;.</p><p>So overload resolution effectively looks like this:</p><pre>Argument:<br>    const Gadget&amp;&amp;<br><br>Candidates:<br><br>Gadget(Gadget&amp;&amp;)<br>       ↑<br>       ❌ can&#39;t bind because argument is const<br><br>Gadget(const Gadget&amp;)<br>       ↑<br>       ✅ can bind<br><br>Result:<br>    COPY</pre><p>Therefore:</p><pre>Gadget h = std::move(g);</pre><p>calls:</p><pre>Gadget(const Gadget&amp;);</pre><h3>4. Compare that with a non-const object</h3><p>If you remove const:</p><pre>Gadget g = build();<br>Gadget h = std::move(g);</pre><p>then std::move(g) has type:</p><pre>Gadget&amp;&amp;</pre><p>Now the move constructor is available:</p><pre>Gadget g<br><br>std::move(g)<br>     ↓<br> Gadget&amp;&amp;<br>     ↓<br>move constructor</pre><p>Compare that with the original:</p><pre>const Gadget g<br><br>std::move(g)<br>     ↓<br>const Gadget&amp;&amp;<br>     ↓<br>Gadget&amp;&amp;       ❌<br>const Gadget&amp;  ✅<br>     ↓<br>copy constructor</pre><h3>5. This matters in real code</h3><p>A useful rule is:</p><blockquote><strong><em>std::move() on a </em></strong><strong><em>const object usually results in a copy, not a move.</em></strong></blockquote><p>For example:</p><pre>std::string s1 = &quot;hello&quot;;<br>std::string s2 = std::move(s1);   // move<br><br>const std::string s3 = &quot;hello&quot;;<br>std::string s4 = std::move(s3);   // copy</pre><p>This can cause subtle performance surprises. For instance, suppose you write:</p><pre>const std::vector&lt;int&gt; result = compute();<br>consume(std::move(result));</pre><p>You may expect the vector’s storage to be transferred, but because result is const, the receiving code generally can&#39;t use the ordinary move constructor.</p><p>If you intend to transfer ownership later, you’d normally write:</p><pre>std::vector&lt;int&gt; result = compute();<br>consume(std::move(result));</pre><p>The most useful mental model is:</p><pre>std::move(x)<br>    =<br>&quot;treat x as an rvalue&quot;<br><br>NOT<br>&quot;move x&quot;</pre><p>And keep this transformation in mind:</p><pre>T             → std::move → T&amp;&amp;<br>const T       → std::move → const T&amp;&amp;</pre><p>So in the example, std::move(g) does make g an rvalue expression, but it remains <strong>const</strong>. The ordinary Gadget(Gadget&amp;&amp;) move constructor can&#39;t accept it, while Gadget(const Gadget&amp;) can. Therefore <strong>the copy constructor wins</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35516e2624d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 10]]></title>
            <link>https://medium.com/@mfnqxfb/c-10-2875e704e9da?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/2875e704e9da</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:34:24 GMT</pubDate>
            <atom:updated>2026-10-24T04:36:23.706Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Given <br>struct Wrapper {<br> Wrapper(int);<br> Wrapper(const Wrapper&amp;);<br> Wrapper(Wrapper&amp;&amp;);<br>};<br>and <br>Wrapper make(int x) { return Wrapper{x}; } <br>called as <br>Wrapper w = make(5);, <br>which is true under C++17 guaranteed copy elision?</blockquote><blockquote>Answer: make(5) is a prvalue materialized directly into w, so no constructor runs after the initial construction</blockquote><p>This question is about <strong>C++17 guaranteed copy elision</strong> and the changed meaning of prvalues.</p><p>Given:</p><pre>struct Wrapper {<br>    Wrapper(int);<br>    Wrapper(const Wrapper&amp;);<br>    Wrapper(Wrapper&amp;&amp;);<br>};<br><br>Wrapper make(int x) {<br>    return Wrapper{x};<br>}<br><br>Wrapper w = make(5);</pre><p>Under C++17, the important result is:</p><blockquote><em>w is constructed directly by </em><em>Wrapper(int). Neither the copy constructor nor the move constructor is called.</em></blockquote><p>Conceptually, although the source code looks like several steps:</p><pre>Wrapper{5}<br>    ↓<br>return from make()<br>    ↓<br>temporary result<br>    ↓<br>move/copy into w</pre><p>C++17’s guaranteed copy-elision rules make it effectively:</p><pre>Wrapper{5}<br>    │<br>    └────────────► construct directly in w</pre><p>So only:</p><pre>Wrapper(int);</pre><p>runs.</p><h3>Step 1: return Wrapper{x};</h3><p>Inside:</p><pre>Wrapper make(int x) {<br>    return Wrapper{x};<br>}</pre><p>Wrapper{x} is a <strong>prvalue</strong> of type Wrapper.</p><p>Before C++17, you could conceptually think of this as creating a temporary:</p><pre>Wrapper temporary{x};<br>return temporary;</pre><p>followed by a move/copy into the function’s return object, although compilers were normally allowed to elide those operations.</p><p>C++17 changed the model. The prvalue doesn’t first have to create a separate temporary Wrapper that is subsequently moved.</p><p>Instead, its initialization is performed directly into the destination storage.</p><p>So:</p><pre>return Wrapper{x};</pre><p>constructs the function’s result object directly.</p><h3>Step 2: What about Wrapper w = make(5)?</h3><p>make(5) is itself a Wrapper prvalue:</p><pre>Wrapper w = make(5);</pre><p>Again, C++17 doesn’t require:</p><pre>make(5)<br>   ↓<br>temporary Wrapper<br>   ↓ move<br>   w</pre><p>Instead, the result is constructed directly into w&#39;s storage.</p><p>Putting both pieces together:</p><pre>make(5)<br><br>    x = 5<br>      │<br>      ▼<br> return Wrapper{x}<br>      │<br>      │<br>      │   no intermediate Wrapper<br>      │   no copy<br>      │   no move<br>      ▼<br>┌────────────────┐<br>│       w        │<br>│                │<br>│ Wrapper(int)   │<br>└────────────────┘</pre><p>So the constructor sequence is simply:</p><pre>Wrapper(int)     ← called once<br>Wrapper(copy)    ← not called<br>Wrapper(move)    ← not called</pre><h3>This is stronger than an optimization</h3><p>This is the key C++17 point.</p><p>Historically, “copy elision” often meant that the compiler was <strong>permitted</strong> to omit a copy/move.</p><p>For these C++17 prvalue cases, however, there isn’t conceptually an intermediate object that needs to be copied/moved. This behavior is guaranteed by the language.</p><p>A striking consequence is that this can compile:</p><pre>struct Wrapper {<br>    Wrapper(int);<br>    Wrapper(const Wrapper&amp;) = delete;<br>    Wrapper(Wrapper&amp;&amp;) = delete;<br>};<br><br>Wrapper make(int x) {<br>    return Wrapper{x};<br>}<br><br>Wrapper w = make(5);   // OK in C++17+</pre><p>Even though Wrapper is neither copyable nor movable.</p><p>Why?</p><p>Because neither operation is needed:</p><pre>Wrapper{5}<br>    │<br>    └────────────► w<br>                   constructed directly</pre><h3>But don’t confuse this with NRVO</h3><p>There’s an important related case:</p><pre>Wrapper make(int x) {<br>    Wrapper temp{x};<br>    return temp;<br>}</pre><p>This is <strong>NRVO</strong> — Named Return Value Optimization.</p><p>Here temp is a named local variable, so return temp; is different from:</p><pre>return Wrapper{x};</pre><p>NRVO is generally permitted but not guaranteed in the same way.</p><p>Compare:</p><pre>Wrapper make1(int x) {<br>    return Wrapper{x};   // C++17 guaranteed elision<br>}</pre><p>versus:</p><pre>Wrapper make2(int x) {<br>    Wrapper temp{x};<br>    return temp;         // NRVO, not mandatory<br>}</pre><p>That’s a common interview distinction.</p><h3>The mental model</h3><p>Before C++17, people often learned prvalues as:</p><pre>create temporary<br>      ↓<br>copy/move temporary<br>      ↓<br>destination</pre><p>For C++17 guaranteed-elision situations, a better model is:</p><pre>prvalue<br>   ↓<br>instructions for initializing<br>the final destination<br>   ↓<br>construct directly there</pre><p>Therefore:</p><pre>Wrapper w = make(5);</pre><p>ultimately results in Wrapper(int) constructing w directly. There is <strong>no subsequent copy or move constructor call</strong>.</p><p>One wording nuance in the provided answer: saying “make(5) is a prvalue materialized directly into w&quot; captures the intended result, though more precisely the prvalue&#39;s result object is w; there isn&#39;t a separate temporary object that is first materialized and then transferred into w.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2875e704e9da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 9]]></title>
            <link>https://medium.com/@mfnqxfb/c-9-3792a6d0f6b7?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/3792a6d0f6b7</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 04:30:00 GMT</pubDate>
            <atom:updated>2026-10-24T04:30:30.785Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>For a local variable T x;, what does decltype((x)) y = x; declare, and why is it a classic interview gotcha?</blockquote><blockquote>Answer: It declares an lvalue reference to T, binding directly to x with no copy</blockquote><p>This question tests a special rule of <strong>decltype</strong>: adding parentheses can change the resulting type.</p><p>Consider:</p><pre>T x;<br>decltype((x)) y = x;</pre><p>The result is:</p><pre>T&amp; y = x;</pre><p>So y is an <strong>lvalue reference</strong> bound directly to x. No new T object is copied.</p><p>The gotcha is that these two expressions produce different types:</p><pre>decltype(x)     // T<br>decltype((x))   // T&amp;</pre><h3>Why?</h3><p>decltype has two sets of rules.</p><p>When its argument is an <strong>unparenthesized variable name</strong>, such as:</p><pre>decltype(x)</pre><p>C++ uses a special rule: the result is the <strong>declared type of </strong><strong>x</strong>.</p><p>If:</p><pre>T x;</pre><p>then:</p><pre>decltype(x)   // T</pre><p>Therefore:</p><pre>decltype(x) y = x;</pre><p>is equivalent to:</p><pre>T y = x;      // copy</pre><p>y is a separate object.</p><p>But once you write:</p><pre>decltype((x))</pre><p>the extra parentheses mean the special “variable name” rule no longer applies. Now decltype examines the <strong>value category of the expression</strong> (x).</p><p>A named variable is an <strong>lvalue expression</strong>, and the general decltype rule is:</p><pre>expression is lvalue  → T&amp;<br>expression is xvalue  → T&amp;&amp;<br>expression is prvalue → T</pre><p>Since:</p><pre>(x)</pre><p>is an lvalue expression of type T:</p><pre>decltype((x))   // T&amp;</pre><p>Therefore:</p><pre>decltype((x)) y = x;</pre><p>means:</p><pre>T&amp; y = x;</pre><h3>You can see the difference by modifying y</h3><p>For example:</p><pre>int x = 10;<br>decltype((x)) y = x;   // int&amp; y = x<br>y = 99;<br>std::cout &lt;&lt; x;         // 99</pre><p>The relationship is:</p><pre>x<br>┌──────────┐<br>│    10    │<br>└──────────┘<br>     ▲<br>     │<br>     y</pre><p>y is simply another name for x.</p><p>Compare that with:</p><pre>int x = 10;<br>decltype(x) y = x;     // int y = x<br>y = 99;<br>std::cout &lt;&lt; x;         // 10</pre><p>Now there are two independent objects:</p><pre>x                 y<br>┌──────┐         ┌──────┐<br>│  10  │         │  99  │<br>└──────┘         └──────┘</pre><h3>Why is this an interview gotcha?</h3><p>Because intuitively:</p><pre>x</pre><p>and:</p><pre>(x)</pre><p>appear to be exactly the same expression. In almost every ordinary context, adding those parentheses changes nothing.</p><p>But decltype deliberately distinguishes them:</p><pre>T x;<br>decltype(x)       // T<br>decltype((x))     // T&amp;</pre><p>This becomes especially important in generic code. For example:</p><pre>auto f() -&gt; decltype(auto) {<br>    int x = 42;<br>    return (x);   // dangerous!<br>}</pre><p>Because the returned expression is (x):</p><pre>decltype((x))   // int&amp;</pre><p>so decltype(auto) deduces the return type as:</p><pre>int&amp;</pre><p>But x is local and is destroyed when f() returns, so the function returns a <strong>dangling reference</strong>.</p><p>The key rule worth memorizing is:</p><pre>decltype(name)<br>    → declared type of name<br><br>decltype((expression))<br>    → inspect value category:<br><br>       lvalue  → T&amp;<br>       xvalue  → T&amp;&amp;<br>       prvalue → T</pre><p>So for this question:</p><pre>T x;<br>decltype((x)) y = x;</pre><p>(x) is an <strong>lvalue</strong>, therefore decltype((x)) is <strong>T&amp;</strong>, and y binds directly to x without making a copy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3792a6d0f6b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 8]]></title>
            <link>https://medium.com/@mfnqxfb/c-8-a23d38f2afbc?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/a23d38f2afbc</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 04:47:06 GMT</pubDate>
            <atom:updated>2026-10-22T04:47:06.724Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Which standard synchronization primitive is a one-shot downward counter that unblocks waiting threads when its counter reaches zero and cannot be reused afterward?<br>Answer: std::latch: a single-use counter that releases waiters when it reaches zero</blockquote><p>std::latch is a C++20 synchronization primitive designed for a common pattern:</p><blockquote><strong><em>Wait until N things have finished, then allow everyone waiting to continue.</em></strong></blockquote><p>The important properties are that its counter only goes <strong>down</strong>, reaching zero releases the waiters, and a latch is <strong>single-use</strong>.</p><p>Consider:</p><pre>#include &lt;latch&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>std::latch done(3);<br><br>void worker(int id)<br>{<br>    std::cout &lt;&lt; &quot;Worker &quot; &lt;&lt; id &lt;&lt; &quot; working\n&quot;;<br>    // do work...<br>    done.count_down();<br>}<br><br>int main()<br>{<br>    std::thread t1(worker, 1);<br>    std::thread t2(worker, 2);<br>    std::thread t3(worker, 3);<br><br>    done.wait();<br><br>    std::cout &lt;&lt; &quot;All workers finished\n&quot;;<br><br>    t1.join();<br>    t2.join();<br>    t3.join();<br>}</pre><p>Initially:</p><pre>latch counter = 3</pre><p>As workers finish:</p><pre>Worker 1 finishes<br>        ↓<br>count_down()<br>        ↓<br>counter = 2<br><br>Worker 3 finishes<br>        ↓<br>count_down()<br>        ↓<br>counter = 1<br><br>Worker 2 finishes<br>        ↓<br>count_down()<br>        ↓<br>counter = 0<br>        ↓<br>all waiters released</pre><p>So the main thread’s:</p><pre>done.wait();</pre><p>blocks until the counter reaches zero.</p><h3>Why call it a “downward counter”?</h3><p>You specify the initial count when constructing it:</p><pre>std::latch latch(5);</pre><p>Then threads can decrease it:</p><pre>latch.count_down();</pre><p>or decrease it by more than one:</p><pre>latch.count_down(2);</pre><p>Conceptually:</p><pre>5 → 4 → 3 → 2 → 1 → 0<br>                    ↑<br>                  OPEN</pre><p>Once it reaches zero, wait() no longer blocks.</p><p>You can think of a latch as a gate:</p><pre>counter &gt; 0<br><br>Thread A ──┐<br>Thread B ──┼──X── blocked<br>Thread C ──┘<br><br>counter == 0<br><br>Thread A ───────►<br>Thread B ───────►<br>Thread C ───────►</pre><h3>arrive_and_wait()</h3><p>There’s also a convenient operation:</p><pre>latch.arrive_and_wait();</pre><p>It is roughly equivalent to:</p><pre>latch.count_down();<br>latch.wait();</pre><p>For example:</p><pre>std::latch ready(3);<br><br>void worker()<br>{<br>    // initialization...<br><br>    ready.arrive_and_wait();<br><br>    // All three have now arrived.<br>    // Continue...<br>}</pre><p>Each thread says:</p><blockquote><em>“I’ve arrived, decrement the counter, and now wait for everybody else.”</em></blockquote><h3>Why can’t it be reused?</h3><p>Once:</p><pre>3 → 2 → 1 → 0</pre><p>there is no operation that resets it back to:</p><pre>0 → 3</pre><p>That’s why std::latch is a <strong>one-shot</strong> synchronization primitive.</p><p>This distinguishes it from std::barrier.</p><p>A useful comparison is:</p><pre><strong>Primitive                Basic idea                           Reusable?</strong><br>std::latch               Wait for N arrivals/completions      ❌<br>std::barrier             All N participants meet at           ✅<br>                         synchronization points<br>std::counting_semaphore  Control access using permits         ✅<br>std::condition_variable  Wait for a condition/state change    ✅</pre><p>For example, if you’re processing something in repeated iterations:</p><pre>Phase 1<br>T1 ──┐<br>T2 ──┼── barrier ──►<br>T3 ──┘<br><br>Phase 2<br>T1 ──┐<br>T2 ──┼── same barrier ──►<br>T3 ──┘<br><br>Phase 3<br>...</pre><p>std::barrier is appropriate.</p><p>But if the requirement is simply:</p><pre>Start 10 workers<br>      ↓<br>wait until all 10 finish initialization<br>      ↓<br>continue once</pre><p>std::latch is a natural fit.</p><h3>One more important point: memory synchronization</h3><p>A latch isn’t merely polling an atomic counter. It also provides memory synchronization.</p><p>If workers write data before count_down():</p><pre>results[i] = compute();<br>done.count_down();</pre><p>and another thread waits:</p><pre>done.wait();<br><br>// safely consume results</pre><p>the latch’s synchronization semantics ensure the relevant preceding work is visible after the successful wait.</p><p>So the easiest mental model is:</p><pre>std::latch(N)<br><br>N<br>↓ count_down()<br>N-1<br>↓<br>...<br>↓<br>1<br>↓ count_down()<br>0<br>↓<br>release all waiters<br><br>DONE — cannot reset</pre><p>That’s why the answer is <strong>std::latch</strong>: it represents a <strong>single-use countdown to zero followed by permanent release</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a23d38f2afbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 7]]></title>
            <link>https://medium.com/@mfnqxfb/c-7-884fdf733b8e?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/884fdf733b8e</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 04:38:37 GMT</pubDate>
            <atom:updated>2026-10-22T04:38:37.483Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Consider:<br><em>struct Widget {<br> int id;<br> void ping();<br>};<br>alignas(Widget)<br>unsigned char buf[sizeof(Widget)];<br>new (buf) Widget{42};<br>Widget* q = reinterpret_cast&lt;Widget*&gt;(buf);<br>q-&gt;ping(); // ??? </em><br>What is wrong with accessing the new object through q?<br>Answer: Undefined behavior: after the new object is created in the storage, the pointer derived from the old unsigned char array does not point to it — the new object is not transparently replaceable, so access requires std::launder (or the pointer returned by placement new).</blockquote><p>This question is about a subtle part of the C++ object model: <strong>object lifetime, placement </strong><strong>new, pointer provenance, and </strong><strong>std::launder</strong>.</p><p>Start with:</p><pre>struct Widget {<br>    int id;<br>    void ping();<br>};<br><br>alignas(Widget) unsigned char buf[sizeof(Widget)];<br>new (buf) Widget{42};<br>Widget* q = reinterpret_cast&lt;Widget*&gt;(buf);<br>q-&gt;ping();   // ???</pre><p>The surprising point is that having the <strong>right address and right alignment does not automatically mean a pointer can be used to access the newly created object</strong>.</p><h3>1. What does buf initially contain?</h3><p>This:</p><pre>alignas(Widget) unsigned char buf[sizeof(Widget)];</pre><p>creates an actual object:</p><pre>buf = unsigned char array object<br>      ┌───────────────────────┐<br>      │ raw bytes             │<br>      └───────────────────────┘<br>      ^<br>      |<br>      buf</pre><p>alignas(Widget) guarantees that the address is suitably aligned for a Widget.</p><p>But at this point there is <strong>no </strong><strong>Widget there</strong>.</p><h3>2. Placement new creates a Widget</h3><p>Then:</p><pre>new (buf) Widget{42};</pre><p>uses placement new.</p><p>Unlike ordinary:</p><pre>new Widget{42}</pre><p>it doesn’t allocate memory. It constructs the Widget in the supplied storage.</p><p>Conceptually:</p><pre>Before:<br><br>address X<br>┌────────────────────┐<br>│ unsigned char[...] │<br>└────────────────────┘<br><br>placement new<br>       ↓<br><br>After:<br>address X<br>┌────────────────────┐<br>│ Widget { id = 42 } │<br>└────────────────────┘</pre><p>So a real Widget now exists at that address.</p><h3>3. Placement new returns the correct pointer</h3><p>This is the simplest way to write the code correctly:</p><pre>Widget* q = new (buf) Widget{42};<br>q-&gt;ping();   // OK</pre><p>Placement new returns a pointer to the object it just created.</p><p>That’s an important point that often gets overlooked.</p><p>Instead, the example throws away that pointer:</p><pre>new (buf) Widget{42};</pre><p>and later manufactures another pointer:</p><pre>Widget* q = reinterpret_cast&lt;Widget*&gt;(buf);</pre><p>That’s where the object-model subtlety arises.</p><h3>4. Isn’t q numerically the same address?</h3><p>Yes.</p><p>You may have:</p><pre>buf address = 0x1000<br>q   address = 0x1000<br>Widget      = 0x1000</pre><p>But in the C++ abstract machine:</p><blockquote><strong><em>same address ≠ necessarily a pointer usable to access the same object.</em></strong></blockquote><p>Pointers have semantics tied to objects and their lifetimes, not merely numerical addresses.</p><p>The pointer expression originated from:</p><pre>buf</pre><p>which refers to the original unsigned char array/storage.</p><p>Then:</p><pre>reinterpret_cast&lt;Widget*&gt;(buf)</pre><p>changes the pointer type, but reinterpret_cast by itself does not perform the lifetime/provenance transition needed to make this pointer denote the newly created Widget in this situation.</p><h3>5. Why doesn’t transparent replacement save us?</h3><p>C++ has rules called <strong>transparent replaceability</strong> that make many ordinary placement-new replacement patterns work naturally.</p><p>For example, roughly:</p><pre>Widget w{1};<br>Widget* p = &amp;w;<br>w.~Widget();<br>new (&amp;w) Widget{2};<br>p-&gt;ping();</pre><p>Under the applicable transparent-replacement rules, an existing pointer can automatically refer to the replacement object.</p><p>But your example is different.</p><p>The original object is:</p><pre>unsigned char[sizeof(Widget)]</pre><p>while the newly created object is:</p><pre>Widget</pre><p>The Widget is being created within the array&#39;s storage; this is not the simple &quot;replace a Widget with another Widget&quot; case that allows the old pointer to transparently retarget to the new object.</p><p>Therefore you can’t simply reason:</p><pre>same storage<br>   +<br>reinterpret_cast<br>   =<br>pointer to new Widget</pre><h3>6. std::launder handles this case</h3><p>You can write:</p><pre>new (buf) Widget{42};<br>Widget* q =<br>    std::launder(reinterpret_cast&lt;Widget*&gt;(buf));<br>q-&gt;ping();</pre><p>std::launder, introduced in C++17, essentially tells the C++ object model:</p><blockquote><em>Find the live object of this type that now exists at this address and give me a pointer suitable for accessing it, subject to </em><em>std::launder&#39;s preconditions.</em></blockquote><p>So conceptually:</p><pre>buf<br> │<br> │ reinterpret_cast<br> ▼<br>Widget* with problematic old-storage association<br> │<br> │ std::launder<br> ▼<br>Widget* referring to newly created Widget<br> │<br> ▼<br>q-&gt;ping()</pre><h3>7. Better: don’t discard the placement-new result</h3><p>In this particular example, there’s usually no reason to use std::launder at all.</p><p>Instead of:</p><pre>new (buf) Widget{42};<br>Widget* q =<br>    std::launder(reinterpret_cast&lt;Widget*&gt;(buf));</pre><p>just do:</p><pre>Widget* q = new (buf) Widget{42};<br>q-&gt;ping();</pre><p>The placement-new expression already gives you exactly the pointer you want.</p><p>And when you’re done, because you used placement new, you must manage destruction appropriately:</p><pre>q-&gt;~Widget();</pre><p>No delete q, because placement new didn&#39;t allocate that storage.</p><h3>8. Why does C++ care about this?</h3><p>This seems unnecessarily strict until compiler optimization enters the picture.</p><p>Suppose a compiler knows a pointer refers to object A. Then you destroy A and create object B at exactly the same address.</p><p>Numerically:</p><pre>A address = 0x1000<br>B address = 0x1000</pre><p>But semantically:</p><pre>A ≠ B</pre><p>Without lifetime rules, the compiler couldn’t reliably determine whether accesses through old pointers refer to the old object, the new object, or storage containing the new object.</p><p>std::launder exists for the relatively rare cases where the optimizer/object model needs an explicit transition.</p><h3>The main idea to remember</h3><p>Don’t think of placement new as merely:</p><pre>put some bytes at this address</pre><p>Think:</p><pre>raw/storage object<br>      ↓<br>placement new<br>      ↓<br>a NEW C++ object&#39;s lifetime begins<br>      ↓<br>use a pointer that denotes that new object</pre><p>So the safest version of this example is simply:</p><pre>alignas(Widget) unsigned char buf[sizeof(Widget)];<br>Widget* q = new (buf) Widget{42};<br>q-&gt;ping();<br>q-&gt;~Widget();</pre><p>And if you’re forced to recover the new object through the old storage pointer in a case where transparent replacement doesn’t apply:</p><pre>Widget* q =<br>    std::launder(reinterpret_cast&lt;Widget*&gt;(buf));</pre><p>The deeper lesson is that in modern C++, <strong>storage, object lifetime, pointer type, and pointer identity/provenance are related but distinct concepts</strong>. A pointer having the correct numerical address and type is not, by itself, always sufficient for legally accessing an object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884fdf733b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 6]]></title>
            <link>https://medium.com/@mfnqxfb/c-6-cb5c448a6f56?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5c448a6f56</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 02:09:06 GMT</pubDate>
            <atom:updated>2026-10-22T02:15:59.812Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Consider:</blockquote><blockquote><em>struct Task {<br> Task(Task&amp;&amp;) noexcept(false); // move may throw<br> Task(const Task&amp;) = delete; /* … */<br>};<br>std::vector&lt;Task&gt; v;<br>v.push_back(Task{}); // triggers reallocation</em></blockquote><blockquote>When the vector reallocates, how are the existing elements transferred, and what guarantee holds?<br>Answer: The elements are moved via the throwing move constructor; if it throws, the vector is left in a valid but unspecified state — only the basic guarantee holds.</blockquote><p>This question tests a subtle interaction between <strong>std::vector reallocation, move semantics, </strong><strong>noexcept, and exception guarantees</strong>.</p><p>Consider:</p><pre>struct Task {<br>    Task(Task&amp;&amp;) noexcept(false);  // move may throw<br>    Task(const Task&amp;) = delete;    // cannot copy<br>};<br>std::vector&lt;Task&gt; v;<br>v.push_back(Task{});  // suppose this causes reallocation</pre><p>The key question is: when vector reallocates, what can it do with the <strong>existing elements</strong>?</p><h3>1. What happens during vector reallocation?</h3><p>Suppose v currently has 3 elements and its capacity is 3:</p><pre>old storage<br>┌──────┬──────┬──────┐<br>│ T0   │ T1   │ T2   │<br>└──────┴──────┴──────┘<br>size = 3, capacity = 3</pre><p>Now another push_back() requires more capacity.</p><p>The vector roughly has to:</p><pre>1. Allocate larger storage<br><br>2. Construct elements in new storage<br>      old T0 → new T0<br>      old T1 → new T1<br>      old T2 → new T2<br>      new Task → new T3<br><br>3. Destroy old elements<br><br>4. Release old storage</pre><p>The interesting part is step 2: <strong>copy or move?</strong></p><h3>2. Normally vector prefers a non-throwing move</h3><p>Imagine:</p><pre>struct Task {<br>    Task(Task&amp;&amp;) noexcept;<br>    Task(const Task&amp;);<br>};</pre><p>Moving is safe because it cannot throw, so the vector can move the existing elements:</p><pre>old                    new<br><br>T0 ─── move ─────────► T0&#39;<br>T1 ─── move ─────────► T1&#39;<br>T2 ─── move ─────────► T2&#39;</pre><p>If all moves are noexcept, reallocation can provide strong exception safety much more easily.</p><p>This is one major reason noexcept on move constructors matters.</p><h3>3. What if move can throw?</h3><p>Our class says:</p><pre>Task(Task&amp;&amp;) noexcept(false);</pre><p>Now moving:</p><pre>Task newTask(std::move(oldTask));</pre><p>might throw.</p><p>For many types, vector can avoid this problem by <strong>copying instead</strong>.</p><p>For example:</p><pre>struct Task {<br>    Task(Task&amp;&amp;) noexcept(false);<br>    Task(const Task&amp;);             // copy available<br>};</pre><p>The implementation can preserve the old elements and construct copies in the new storage:</p><pre>old                    new<br><br>T0 ─── copy ─────────► T0&#39;<br>T1 ─── copy ─────────► T1&#39;<br>T2 ─── copy ─────────► T2&#39;</pre><p>Suppose copying T1 throws. The vector can destroy whatever it constructed in the new storage and leave the old storage intact:</p><pre>old<br>┌──────┬──────┬──────┐<br>│ T0   │ T1   │ T2   │<br>└──────┴──────┴──────┘<br>unchanged</pre><p>That’s how the strong guarantee can be preserved.</p><p>This behavior is closely related to std::move_if_noexcept.</p><h3>4. But our Task cannot be copied</h3><p>Here’s the crucial combination:</p><pre>Task(Task&amp;&amp;) noexcept(false); // move may throw<br>Task(const Task&amp;) = delete;   // copy impossible</pre><p>Vector has two choices:</p><pre>              Existing Task<br>                     │<br>              ┌──────┴──────┐<br>              ▼             ▼<br>            copy           move<br>              │             │<br>           deleted       may throw<br>              ✗             ✓</pre><p>It can’t copy.</p><p>Therefore it has no choice but to move the existing elements despite the fact that moving may throw.</p><h3>5. Why can this break the strong guarantee?</h3><p>Suppose we start with:</p><pre>OLD STORAGE<br><br>T0    T1    T2</pre><p>Reallocation begins.</p><p>First:</p><pre>T0 ─── move ───► T0&#39;</pre><p>Success.</p><p>But moving from T0 may have modified T0. A moved-from object is valid, but its state may have changed:</p><pre>OLD                 NEW<br><br>T0(moved-from) ───► T0&#39;<br>T1<br>T2</pre><p>Then:</p><pre>T1 ─── move ───► T1&#39;</pre><p>Success.</p><p>Now:</p><pre>OLD                 NEW<br><br>T0(moved-from)      T0&#39;<br>T1(moved-from)      T1&#39;<br>T2</pre><p>Now suppose moving T2 throws:</p><pre>Task(std::move(T2));   // 💥 exception</pre><p>The vector can destroy:</p><pre>T0&#39;<br>T1&#39;</pre><p>and free the new storage.</p><p>But there’s a problem.</p><p>The original T0 and T1 have already been moved from:</p><pre>OLD<br>┌───────────────┬───────────────┬──────┐<br>│ T0 moved-from │ T1 moved-from │ T2   │<br>└───────────────┴───────────────┴──────┘</pre><p>There is no general way to restore their previous values.</p><p>So the operation cannot simply roll back to the exact original vector.</p><p>That’s why the <strong>strong guarantee cannot generally be provided</strong> in this situation.</p><h3>6. Basic vs. strong guarantee</h3><p>The distinction is:</p><p><strong>Strong guarantee</strong></p><pre>operation succeeds<br>        ↓<br>new state<br><br>OR<br><br>operation throws<br>        ↓<br>original state completely unchanged</pre><p>This is effectively transactional behavior.</p><p><strong>Basic guarantee</strong></p><pre>operation throws<br>        ↓<br>object is still valid<br>but its exact contents/state may have changed</pre><p>For this scenario, because the vector is forced to use potentially throwing moves, an exception during transfer can leave already-moved elements changed.</p><p>Hence the answer describes it as only the <strong>basic guarantee / valid but unspecified state</strong> rather than rollback to the original contents.</p><h3>7. Why noexcept on move constructors is important</h3><p>Compare three classes:</p><pre>// Case 1<br>struct A {<br>    A(A&amp;&amp;) noexcept;<br>    A(const A&amp;) = delete;<br>};</pre><p>Vector can safely move.</p><pre>// Case 2<br>struct B {<br>    B(B&amp;&amp;) noexcept(false);<br>    B(const B&amp;);<br>};</pre><p>Vector can generally choose copying during reallocation to protect itself from a throwing move.</p><p>But:</p><pre>// Case 3<br>struct C {<br>    C(C&amp;&amp;) noexcept(false);<br>    C(const C&amp;) = delete;<br>};</pre><p>Vector is stuck:</p><pre>copy?   impossible<br>move?   possible, but may throw</pre><p>So it has to take the risky route.</p><p>A useful approximation is:</p><pre>if constexpr (std::is_nothrow_move_constructible_v&lt;T&gt; ||<br>              !std::is_copy_constructible_v&lt;T&gt;)<br>{<br>    move elements;<br>}<br>else<br>{<br>    copy elements;<br>}</pre><p>This is essentially the idea behind:</p><pre>std::move_if_noexcept(x)</pre><p>which behaves approximately as:</p><pre>                Is move noexcept?<br>                  /           \<br>                yes            no<br>                /               \<br>             move          Is copy available?<br>                              /       \<br>                            yes        no<br>                            /           \<br>                          copy          move</pre><p>Your Task follows the bottom-right path:</p><pre>move may throw<br>     +<br>copy deleted<br>     ↓<br>must move<br>     ↓<br>move may fail after earlier elements<br>have already been moved-from<br>     ↓<br>cannot guarantee rollback</pre><p>This is one reason that when designing movable resource-owning C++ classes, you should make the move constructor noexcept <strong>whenever it genuinely cannot throw</strong>:</p><pre>Task(Task&amp;&amp;) noexcept;</pre><p>It isn’t merely documentation. Standard containers can use that information to choose safer and often faster strategies during operations such as reallocation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5c448a6f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 5]]></title>
            <link>https://medium.com/@mfnqxfb/c-5-f3906cadda8a?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3906cadda8a</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 01:56:59 GMT</pubDate>
            <atom:updated>2026-10-22T01:56:59.627Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Two templates: <br>template &lt;typename T&gt; auto a(T t) -&gt; decltype(t.size(), int{}) { return t.size(); } // (A)<br>template &lt;typename T&gt; int b(T t) { return t.size(); } // (B)`<br>For a T with no size() member, which statement is true?<br>Answer: (A) is removed from the overload set by SFINAE, but (B) — if selected — produces a hard error: SFINAE applies only to failures in the immediate context of substitution, not to errors in the instantiated function body.</blockquote><p>This question is testing a crucial detail of <strong>SFINAE</strong>: <em>where</em> template substitution fails determines whether the compiler quietly rejects that overload or gives you a compilation error.</p><p>We have:</p><pre>template &lt;typename T&gt;<br>auto a(T t) -&gt; decltype(t.size(), int{}) {<br>    return t.size();<br>} // (A)<br><br>template &lt;typename T&gt;<br>int b(T t) {<br>    return t.size();<br>} // (B)</pre><p>Now suppose:</p><pre>struct Foo {};<br>Foo x;<br>a(x);<br>b(x);</pre><p>Foo has no size() member.</p><h3>1. What happens with a()?</h3><p>Look at its return type:</p><pre>decltype(t.size(), int{})</pre><p>This uses the <strong>comma operator</strong> inside decltype.</p><p>If t.size() is valid, then:</p><pre>(t.size(), int{})</pre><p>has type int, because the comma operator&#39;s result is its right-hand operand.</p><p>So for a type that has size():</p><pre>struct Good {<br>    int size() const;<br>};</pre><p>the template effectively becomes:</p><pre>int a(Good t) {<br>    return t.size();<br>}</pre><p>But now try:</p><pre>struct Foo {};<br>a(Foo{});</pre><p>During template argument deduction:</p><pre>T = Foo</pre><p>the compiler substitutes Foo into the function declaration:</p><pre>decltype(t.size(), int{})</pre><p>and discovers:</p><pre>Foo has no member named size</pre><p>Critically, this error occurs while substituting into the function’s <strong>immediate context</strong> — its return type.</p><p>Therefore SFINAE applies:</p><blockquote><em>Substitution Failure Is Not An Error.</em></blockquote><p>The compiler does not report the missing size() as a fatal error at this point. Instead, it simply removes this specialization of a from consideration.</p><p>Conceptually:</p><pre>a(Foo{})<br>        T = Foo<br>           │<br>           ▼<br>decltype(t.size(), int{})<br>           │<br>           ▼<br>    Does Foo::size exist?<br>           │<br>          NO<br>           │<br>           ▼<br>   substitution failure<br>           │<br>           ▼<br>remove a&lt;Foo&gt; from overload set</pre><p>If there’s another viable overload, it may be selected.</p><p>For example:</p><pre>template &lt;typename T&gt;<br>auto a(T t) -&gt; decltype(t.size(), int{}) {<br>    return t.size();<br>}<br><br>void a(...) {<br>    std::cout &lt;&lt; &quot;fallback&quot;;<br>}</pre><p>Then:</p><pre>a(Foo{});   // fallback selected</pre><p>This is exactly what SFINAE was historically useful for.</p><h3>2. What happens with b()?</h3><p>Now look at:</p><pre>template &lt;typename T&gt;<br>int b(T t) {<br>    return t.size();<br>}</pre><p>Call:</p><pre>b(Foo{});</pre><p>Template argument deduction itself is perfectly successful:</p><pre>T = Foo</pre><p>The function declaration becomes:</p><pre>int b(Foo t);</pre><p>Nothing is wrong with that declaration.</p><p>So b&lt;Foo&gt; is a valid candidate and can be selected.</p><p>Only <strong>after it is selected and its body is instantiated</strong> does the compiler encounter:</p><pre>return t.size();</pre><p>which becomes essentially:</p><pre>Foo t;<br>return t.size();<br>         ^^^^<br>         doesn&#39;t exist</pre><p>Now you get a hard compilation error.</p><p>SFINAE does <strong>not</strong> rescue you here.</p><h3>3. Why the difference?</h3><p>Compare where the invalid expression occurs.</p><p>For a:</p><pre>template &lt;typename T&gt;<br>auto a(T t) -&gt; decltype(t.size(), int{})<br>                     ^^^^^^^^<br>                     declaration</pre><p>For b:</p><pre>template &lt;typename T&gt;<br>int b(T t) {<br>    return t.size();<br>             ^^^^^^^^<br>             function body<br>}</pre><p>That’s the key distinction:</p><pre>           Invalid expression<br>                    │<br>           ┌────────┴────────┐<br>           │                 │<br>           ▼                 ▼<br>   Immediate context     Function body<br>           │                 │<br>           ▼                 ▼<br>        SFINAE           Hard error<br>           │<br>           ▼<br> candidate removed</pre><h3>4. What does “immediate context” mean?</h3><p>Roughly, it means the types and expressions involved directly in substituting template arguments into the function template’s declaration.</p><p>Typical SFINAE locations include parameter types and return types:</p><pre>template &lt;typename T&gt;<br>auto f(T t) -&gt; decltype(t.foo());</pre><p>or historically:</p><pre>template &lt;<br>    typename T,<br>    typename = std::enable_if_t&lt;some_condition&lt;T&gt;&gt;<br>&gt;<br>void f(T);</pre><p>If substitution directly into those parts fails, SFINAE can discard the specialization.</p><p>But an error discovered later while instantiating:</p><pre>{<br>    // function body<br>}</pre><p>is generally not a substitution failure in the immediate context.</p><h3>5. Why decltype(t.size(), int{})?</h3><p>There’s another trick hidden in the question.</p><p>Why not simply write:</p><pre>decltype(t.size())</pre><p>Because then the return type would depend on whatever size() returns.</p><p>Instead:</p><pre>decltype(t.size(), int{})</pre><p>uses the comma operator:</p><pre>t.size(), int{}</pre><p>The left side must be a valid expression:</p><pre>t.size()</pre><p>but the type of the entire comma expression comes from:</p><pre>int{}</pre><p>so the return type is int.</p><p>It therefore expresses:</p><blockquote><em>“This function exists only if </em><em>t.size() is a valid expression, and if it is, my return type is </em><em>int.&quot;</em></blockquote><p>This was a common pre-C++20 detection technique.</p><h3>6. Modern C++20 version</h3><p>With concepts, the intention is much clearer:</p><pre>template &lt;typename T&gt;<br>requires requires(T t) {<br>    t.size();<br>}<br>int a(T t) {<br>    return t.size();<br>}</pre><p>or:</p><pre>template &lt;typename T&gt;<br>concept HasSize = requires(T t) {<br>    t.size();<br>};<br><br>template &lt;HasSize T&gt;<br>int a(T t) {<br>    return t.size();<br>}</pre><p>Now:</p><pre>struct A {<br>    int size() const { return 10; }<br>};<br>struct B {};<br>a(A{});   // OK<br>a(B{});   // constraint not satisfied</pre><p>The conceptual evolution is:</p><pre>C++11/14/17<br>SFINAE + decltype<br>    ↓<br>&quot;Make substitution fail if size() doesn&#39;t exist&quot;<br><br>C++20+<br>requires / concepts<br>    ↓<br>&quot;Explicitly require that size() exists&quot;</pre><p>So the main interview takeaway is:</p><blockquote><strong><em>SFINAE protects errors encountered during substitution in the immediate context of the function template declaration. It does not generally protect errors that occur later when the selected function’s body is instantiated.</em></strong></blockquote><p>Thus (A) disappears as a candidate when T::size() doesn&#39;t exist, while (B), once selected, fails to compile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3906cadda8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 4]]></title>
            <link>https://medium.com/@mfnqxfb/c-4-eee2713773ed?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee2713773ed</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 01:49:21 GMT</pubDate>
            <atom:updated>2026-10-22T01:49:21.878Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Consider: <br>template &lt;typename T&gt; void log(T&amp;&amp; value) { /* … */ } log(42); // (A) log({1, 2, 3}); // (B) <br>What is true about (B), and what is the idiomatic fix?<br>Answer: Ill-formed: a braced-init-list is a non-deduced context for T&amp;&amp;, so deduction fails. Add an overload taking std::initializer_list&lt;T&gt; (or take the list by value).</blockquote><p>This question tests an important corner case involving <strong>forwarding references</strong> and <strong>braced initializer lists</strong>.</p><p>Start with:</p><pre>template &lt;typename T&gt;<br>void log(T&amp;&amp; value) {<br>    /* ... */<br>}</pre><p>and:</p><pre>log(42);          // (A)<br>log({1, 2, 3});   // (B)</pre><h3>1. Why does log(42) work?</h3><p>Here:</p><pre>log(42);</pre><p>42 is an int prvalue. Template argument deduction can determine:</p><pre>T = int</pre><p>so the instantiated parameter becomes:</p><pre>void log(int&amp;&amp; value);</pre><p>No problem.</p><p>Also, because T&amp;&amp; contains a deduced T, this is a <strong>forwarding reference</strong>:</p><pre>template &lt;typename T&gt;<br>void log(T&amp;&amp; value);</pre><p>It can accept both lvalues and rvalues.</p><p>For example:</p><pre>int x = 42;<br><br>log(x);   // T = int&amp;, parameter collapses to int&amp;<br>log(42);  // T = int,  parameter is int&amp;&amp;</pre><h3>2. Why doesn’t {1, 2, 3} work?</h3><p>This is the interesting part:</p><pre>log({1, 2, 3});</pre><p>You might expect the compiler to think:</p><pre>{1, 2, 3}<br>    ↓<br>std::initializer_list&lt;int&gt;</pre><p>But that’s <strong>not generally how template argument deduction works</strong>.</p><p>A raw braced-init-list:</p><pre>{1, 2, 3}</pre><p>doesn’t have an ordinary type that template deduction can simply inspect.</p><p>In particular, it is not automatically an expression of type:</p><pre>std::initializer_list&lt;int&gt;</pre><p>Therefore, when the compiler sees:</p><pre>template &lt;typename T&gt;<br>void log(T&amp;&amp; value);<br>log({1, 2, 3});</pre><p>it effectively asks:</p><pre>What is T?<br>T&amp;&amp;  ←  {1, 2, 3}<br>???</pre><p>There isn’t enough information to deduce T.</p><p>So compilation fails.</p><h3>3. But std::initializer_list&lt;int&gt; can accept it</h3><p>If you explicitly write:</p><pre>std::initializer_list&lt;int&gt; x = {1, 2, 3};</pre><p>that’s valid because the <strong>destination type is already known</strong>.</p><p>Likewise:</p><pre>void f(std::initializer_list&lt;int&gt; x);<br><br>f({1, 2, 3});   // OK</pre><p>The compiler knows that the parameter expects an:</p><pre>std::initializer_list&lt;int&gt;</pre><p>and constructs one from the braces.</p><p>This is different from:</p><pre>template &lt;typename T&gt;<br>void log(T&amp;&amp;);<br><br>log({1, 2, 3});</pre><p>where the compiler is trying to discover what T should be.</p><h3>4. The idiomatic solution</h3><p>Add an initializer_list overload:</p><pre>template &lt;typename T&gt;<br>void log(T&amp;&amp; value) {<br>    // general case<br>}<br>template &lt;typename T&gt;<br>void log(std::initializer_list&lt;T&gt; values) {<br>    // initializer-list case<br>}</pre><p>Now:</p><pre>log(42);</pre><p>uses the first overload, while:</p><pre>log({1, 2, 3});</pre><p>uses:</p><pre>log(std::initializer_list&lt;T&gt;)</pre><p>and template deduction can determine:</p><pre>T = int</pre><p>because std::initializer_list&lt;T&gt; gets special treatment during deduction from a braced-init-list.</p><p>So:</p><pre>log({1, 2, 3});</pre><p>becomes conceptually:</p><pre>log&lt;int&gt;(std::initializer_list&lt;int&gt;{1, 2, 3});</pre><h3>5. Why can initializer_list&lt;T&gt; deduce T, but T&amp;&amp; cannot?</h3><p>Compare these two templates:</p><pre>template &lt;typename T&gt;<br>void f(T&amp;&amp;);<br><br>template &lt;typename T&gt;<br>void g(std::initializer_list&lt;T&gt;);</pre><p>Then:</p><pre>f({1, 2, 3});   // ERROR<br>g({1, 2, 3});   // OK, T = int</pre><p>C++ has a special template-deduction rule for parameters of type std::initializer_list&lt;T&gt; (and certain array-reference forms): it can examine the elements of the braced list and deduce T.</p><p>There is no corresponding rule for arbitrary T&amp;&amp;.</p><p>A useful mental model is:</p><pre>              {1, 2, 3}<br>                  │<br>          ┌───────┴────────┐<br>          ▼                ▼<br>        T&amp;&amp;        initializer_list&lt;T&gt;<br>          │                │<br>    Can&#39;t deduce       examine elements<br>          │                │<br>        ERROR           T = int</pre><h3>One subtle correction to the wording</h3><p>The answer says:</p><blockquote><em>“a braced-init-list is a non-deduced context for </em><em>T&amp;&amp;&quot;</em></blockquote><p>That’s a useful shorthand, but the precise rule is that when the argument is an initializer list and the parameter is <strong>not</strong> one of the forms for which initializer-list deduction is supported, the parameter is treated as a non-deduced context.</p><p>The main rule to remember is:</p><pre>template&lt;class T&gt; void f(T&amp;&amp;);<br>f({1,2,3});                         // ❌ cannot deduce T<br><br>template&lt;class T&gt;<br>void g(std::initializer_list&lt;T&gt;);<br>g({1,2,3});                         // ✅ T = int</pre><p>And if you really wanted to use the original log(T&amp;&amp;), you could also give the braces an explicit type:</p><pre>log(std::initializer_list&lt;int&gt;{1, 2, 3}); // OK</pre><p>Now the argument is a typed std::initializer_list&lt;int&gt; expression, so T can be deduced normally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee2713773ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 3]]></title>
            <link>https://medium.com/@mfnqxfb/c-3-937c3fd84005?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/937c3fd84005</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 01:41:27 GMT</pubDate>
            <atom:updated>2026-10-22T01:41:27.159Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In std::vector&lt;std::string&gt; v; v.push_back(std::string(&quot;hi&quot;));, which overload is selected and why does it matter?<br>Answer: The string&amp;&amp; overload; the temporary is moved, avoiding a copy</blockquote><p>This question tests <strong>rvalue references, overload resolution, and move semantics</strong> in C++.</p><p>Consider:</p><pre>std::vector&lt;std::string&gt; v;<br>v.push_back(std::string(&quot;hi&quot;));</pre><p>Conceptually, std::vector&lt;T&gt; has these two push_back overloads:</p><pre>void push_back(const T&amp; value);  // copy version<br>void push_back(T&amp;&amp; value);       // move version</pre><p>For this vector, T = std::string, so they become:</p><pre>void push_back(const std::string&amp; value);<br>void push_back(std::string&amp;&amp; value);</pre><p>The question is: <strong>which one does </strong><strong>std::string(&quot;hi&quot;) select?</strong></p><h3>1. std::string(&quot;hi&quot;) is a temporary</h3><p>This expression:</p><pre>std::string(&quot;hi&quot;)</pre><p>constructs a temporary std::string.</p><p>You can think of:</p><pre>v.push_back(std::string(&quot;hi&quot;));</pre><p>as approximately:</p><pre>// unnamed temporary string containing &quot;hi&quot;<br>v.push_back(TEMPORARY);</pre><p>A temporary like this is an <strong>rvalue</strong> — more precisely, a prvalue.</p><p>Therefore, it is an excellent match for:</p><pre>std::string&amp;&amp;</pre><p>and overload resolution chooses:</p><pre>void push_back(std::string&amp;&amp; value);</pre><p>rather than:</p><pre>void push_back(const std::string&amp; value);</pre><h3>2. Why does std::string&amp;&amp; matter?</h3><p>It allows vector to <strong>move</strong> the string into its internal storage rather than copy it.</p><p>Conceptually:</p><pre>void push_back(std::string&amp;&amp; value)<br>{<br>    // construct vector element from value<br>    new (location) std::string(std::move(value));<br>}</pre><p>Suppose the temporary string internally owns dynamically allocated memory:</p><pre>temporary string<br>┌───────────────┐<br>│ ptr ──────────┼──────► &quot;a very long string...&quot;<br>│ size = 21     │<br>└───────────────┘</pre><p>With a copy, another allocation and character copy may be needed:</p><pre>temporary                         vector element<br>    │                                  │<br>    ▼                                  ▼<br>&quot;a very long string...&quot;       &quot;a very long string...&quot;<br>       allocation + copy ───────►</pre><p>With a move, the new std::string can typically take ownership of the temporary&#39;s resources:</p><pre>Before move:<br><br>temporary<br>    │<br>    └────► string storage<br><br>After move:<br><br>temporary                  vector element<br>                               │<br>                               └────► string storage</pre><p>The temporary is going to be destroyed immediately anyway, so transferring its resources is appropriate.</p><p>For short strings such as &quot;hi&quot;, <strong>small-string optimization (SSO)</strong> usually means there&#39;s no heap allocation to steal, so the practical performance difference may be tiny. The language-level answer is still the same: the rvalue overload is selected and the element is move-constructed.</p><h3>3. Compare it with an lvalue</h3><p>Now consider:</p><pre>std::string s = &quot;hi&quot;;<br>v.push_back(s);</pre><p>s is a named variable, and therefore an <strong>lvalue</strong>.</p><p>So:</p><pre>v.push_back(s);</pre><p>selects:</p><pre>push_back(const std::string&amp;);</pre><p>and copies s.</p><p>Afterward:</p><pre>s              → &quot;hi&quot;<br>v[0]           → &quot;hi&quot;<br><br>Both remain independent strings.</pre><p>But if you explicitly say:</p><pre>v.push_back(std::move(s));</pre><p>std::move(s) converts the expression into an xvalue, allowing:</p><pre>push_back(std::string&amp;&amp;);</pre><p>to be selected.</p><p>Now the string is moved:</p><pre>s ───────────────┐<br>                 │ std::move<br>                 ▼<br>              vector</pre><p>After the move, s is still <strong>valid</strong>, but its contents are generally unspecified. You can destroy it or assign another value to it safely, but shouldn&#39;t assume it is empty.</p><h3>4. The three cases are worth memorizing</h3><pre>std::string s = &quot;hello&quot;;<br>v.push_back(s);                    // COPY<br>v.push_back(std::move(s));         // MOVE<br>v.push_back(std::string(&quot;hello&quot;)); // MOVE</pre><p>Think of them as:</p><pre>Expression                   Value category     Selected overload<br>s                            lvalue             const string&amp;<br>std::move(s)                 xvalue             string&amp;&amp;<br>std::string(&quot;hello&quot;)         prvalue            string&amp;&amp;</pre><p>Both xvalues and prvalues are rvalues and can bind to T&amp;&amp;.</p><h3>5. What about emplace_back?</h3><p>You could make the original code even simpler:</p><pre>v.emplace_back(&quot;hi&quot;);</pre><p>Instead of first conceptually creating a std::string argument and then moving it into the vector, emplace_back constructs the element directly from &quot;hi&quot;:</p><pre>push_back:<br><br>&quot;hi&quot;<br> ↓<br>temporary std::string<br> ↓ move<br>vector&#39;s std::string<br><br>emplace_back:<br>&quot;hi&quot;<br> ↓<br>vector&#39;s std::string</pre><p>Modern compilers and library implementations can make the practical difference small, but this illustrates the purpose of emplace_back.</p><p>So the interview answer:</p><blockquote><strong><em>The </em></strong><strong><em>string&amp;&amp; overload is selected; the temporary is moved, avoiding a copy.</em></strong></blockquote><p>is testing whether you recognize the chain:</p><pre>std::string(&quot;hi&quot;)<br>       ↓<br>temporary / prvalue<br>       ↓<br>rvalue<br>       ↓<br>binds preferentially to std::string&amp;&amp;<br>       ↓<br>push_back(T&amp;&amp;)<br>       ↓<br>move construction</pre><p>This is one of the fundamental applications of <strong>C++11 move semantics</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=937c3fd84005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ 2]]></title>
            <link>https://medium.com/@mfnqxfb/c-2-7dac7d8c7534?source=rss-98e19a3a8100------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dac7d8c7534</guid>
            <dc:creator><![CDATA[W]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 01:34:42 GMT</pubDate>
            <atom:updated>2026-10-22T01:34:42.112Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Your copy-assignment does delete[] data; data = new char[n]; /* copy */. What exception safety does it provide? <br>Answer: Only the basic guarantee; use copy-and-swap for the strong guarantee</blockquote><p>This question is about <strong>exception safety in C++ resource-managing classes</strong>. The key issue is what happens if new throws an exception <em>after you&#39;ve already destroyed the object&#39;s old data</em>.</p><p>Suppose we have:</p><pre>class Buffer {<br>    char* data;<br>    std::size_t size;<br><br>public:<br>    Buffer&amp; operator=(const Buffer&amp; rhs) {<br>        delete[] data;<br>        size = rhs.size;<br>        data = new char[size];     // &lt;-- might throw<br>        std::copy(rhs.data, rhs.data + size, data);<br>        return *this;<br>    }<br>};</pre><p>At first glance this seems reasonable:</p><pre>delete old data<br>      ↓<br>allocate new data<br>      ↓<br>copy rhs data</pre><p>But exceptions make this dangerous.</p><h3>1. What happens if new fails?</h3><p>new char[size] can throw std::bad_alloc.</p><p>Imagine:</p><pre>Buffer a;    // contains &quot;Hello&quot;<br>Buffer b;    // contains a huge amount of data<br><br>a = b;</pre><p>Inside a.operator=(b):</p><pre>delete[] data;          // &quot;Hello&quot; is destroyed<br>size = rhs.size;<br>data = new char[size];  // 💥 std::bad_alloc</pre><p>The assignment never completes.</p><p>More importantly, the <strong>original state of </strong><strong>a has already been destroyed</strong>.</p><p>Before:</p><pre>a<br>┌──────────────┐<br>│ size = 5     │<br>│ data ────────┼──► &quot;Hello&quot;<br>└──────────────┘</pre><p>After delete[] data:</p><pre>a<br>┌──────────────┐<br>│ size = ?     │<br>│ data ────────┼──► FREED MEMORY<br>└──────────────┘</pre><p>If new now throws, a cannot be restored to &quot;Hello&quot;.</p><p>In fact, <strong>this exact implementation may not even satisfy the basic guarantee</strong> because data is still a dangling pointer; when a is eventually destroyed, its destructor may call delete[] data again, causing undefined behavior.</p><p>So the interview answer is assuming the implementation at least leaves the object valid — for example by nulling/resetting members appropriately. The important distinction they are testing is <strong>basic vs. strong exception safety</strong>.</p><h3>2. Basic vs. strong guarantee</h3><p>The usual exception-safety levels are:</p><p>No guarantee: Object may be corrupted<br><strong>Basic: </strong>Object remains valid, but its value may have changed<br><strong>Strong: </strong>Object remains exactly as it was before the operation<br>No-throw: Operation cannot throw</p><p>For assignment, the <strong>strong guarantee</strong> is especially desirable:</p><pre>a = b;</pre><p>should behave conceptually like a transaction:</p><pre>Success → a becomes b<br>Failure → a remains unchanged</pre><p>The naive delete-first approach cannot provide that because it destroys a before knowing whether the rest of the operation will succeed.</p><h3>3. Copy-and-swap solves this</h3><p>A classic implementation is:</p><pre>class Buffer {<br>    char* data;<br>    std::size_t size;<br><br>public:<br>    Buffer(const Buffer&amp; other)<br>        : data(new char[other.size]),<br>          size(other.size)<br>    {<br>        std::copy(other.data,<br>                  other.data + size,<br>                  data);<br>    }<br><br>    void swap(Buffer&amp; other) noexcept {<br>        std::swap(data, other.data);<br>        std::swap(size, other.size);<br>    }<br><br>    Buffer&amp; operator=(Buffer other) {<br>        swap(other);<br>        return *this;<br>    }<br>};</pre><p>Notice the unusual signature:</p><pre>Buffer&amp; operator=(Buffer other)</pre><p>rather than:</p><pre>Buffer&amp; operator=(const Buffer&amp; other)</pre><p>The argument is passed <strong>by value</strong>, so C++ first constructs a copy.</p><p>Suppose:</p><pre>a = b;</pre><p>C++ effectively does:</p><pre>                  Copy constructor<br>                        │<br>                        ▼<br>b ───────────────────► temporary<br><br>a = temporary</pre><p>If allocation fails while constructing the temporary:</p><pre>new char[other.size]  // 💥</pre><p>the assignment operator hasn’t even started.</p><p>Therefore:</p><pre>a = &quot;Hello&quot;<br>      │<br>      │ try copying b<br>      ▼<br> temporary construction<br>      │<br>      ├── SUCCESS ──► swap<br>      │<br>      └── EXCEPTION<br>             │<br>             ▼<br>       a still &quot;Hello&quot;</pre><p>That’s the <strong>strong exception guarantee</strong>.</p><h3>4. Why does swap() matter?</h3><p>Once the temporary has been successfully created:</p><pre>Buffer&amp; operator=(Buffer other) {<br>    swap(other);<br>    return *this;<br>}</pre><p>Suppose:</p><pre>a.data     → &quot;Hello&quot;<br>other.data → &quot;Goodbye&quot;</pre><p>After swap(other):</p><pre>a.data     → &quot;Goodbye&quot;<br>other.data → &quot;Hello&quot;</pre><p>Then other goes out of scope and its destructor deletes &quot;Hello&quot;.</p><p>So instead of:</p><pre>destroy old<br>allocate new       ← dangerous ordering<br>copy</pre><p>we effectively do:</p><pre>allocate new<br>copy<br>      ↓<br>everything succeeded?<br>      ↓ yes<br>swap<br>      ↓<br>destroy old</pre><p>The potentially throwing work occurs <strong>before modifying the destination object</strong>.</p><p>That’s the central idea.</p><h3>5. A useful general principle</h3><p>This pattern goes beyond copy assignment. Strong exception safety often follows the strategy:</p><pre>PREPARE<br>   │<br>   │ potentially throwing work<br>   ▼<br>COMMIT<br>   │<br>   │ noexcept operation<br>   ▼<br>DONE</pre><p>Copy-and-swap implements exactly this:</p><pre>Copy       = prepare<br>Swap       = commit<br>Destructor = cleanup</pre><p>So when you see the interview question:</p><blockquote><em>delete[] data; data = new char[n]; /* copy */ — what exception safety does this provide?</em></blockquote><p>the intended reasoning is:</p><p><strong>The old state is destroyed before the potentially throwing allocation, so the strong guarantee is impossible. Construct the replacement first and commit it with a non-throwing swap to obtain the strong guarantee.</strong></p><p>One caveat worth remembering: a literal delete[] data; data = new ... implementation that leaves data dangling on allocation failure can actually fall <strong>below the basic guarantee</strong>. A well-written “basic guarantee” version must still ensure the object remains destructible and internally valid.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dac7d8c7534" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>