<?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"><channel><title><![CDATA[Stack to Future]]></title><description><![CDATA[I am Pawel, and you can also find me on GitHub, where I am a contributor to some well-known IPCs like iceoryx2 and new movements in the automotive world, such a]]></description><link>https://stacktofuture.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 18 Apr 2026 21:26:19 GMT</lastBuildDate><atom:link href="https://stacktofuture.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[std::unique_ptr  and Rust]]></title><description><![CDATA[If you are a first-time reader of my blog series, warm welcome to you! 😊 I recommend that you spend 30 seconds reading the Introduction, which explains how articles are created.
Takeaways
Today I would like to discuss about replacement for std::uniq...]]></description><link>https://stacktofuture.com/stduniqueptr-and-rust</link><guid isPermaLink="true">https://stacktofuture.com/stduniqueptr-and-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[C++]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Paweł Rutka]]></dc:creator><pubDate>Mon, 20 Oct 2025 20:31:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1759869794339/d2eda5d7-5478-428b-8ca9-eca316156df2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are a first-time reader of my blog series, warm welcome to you! 😊 I recommend that you spend 30 seconds reading the <a target="_blank" href="https://stacktofuture.hashnode.dev/introduction">Introduction</a>, which explains how articles are created.</p>
<h1 id="heading-takeaways">Takeaways</h1>
<p>Today I would like to discuss about replacement for <code>std::unique_ptr</code> in Rust. We will focus on similarities and differences, along with some extensions that we find in Rust. After the reading, you shall:</p>
<ul>
<li><p>have a clear path for transition from C++ to Rust when writing/rewriting code and looking for similar constructs,</p>
</li>
<li><p>know similarities between C++ and Rust when it comes to unique ownership of dynamic allocation</p>
</li>
<li><p>The seed to continue exploring Rust around this topic</p>
</li>
</ul>
<h1 id="heading-intro">Intro</h1>
<p>Back in the old days, we all used to use plain old pointers in C++. Probably many of us knew that this always leads to many issues and came up with different abstractions to solve the problems until the C++ Standards Committee introduced <code>std::unique_ptr</code> in C++11 (with extensions in C++14). From the moment it landed in major compilers (i.e., GCC 4.5, who still remembers it?), it became the main way to manage dynamically allocated memory with ownership being taken care of.</p>
<p>By contrast, in Rust, pointers were never a real problem because, from the beginning and by design, they cannot be <a class="post-section-overview" href="#notes-unsafe">dereferenced<sup>1</sup></a>. Nevertheless, dynamic allocation and ownership of underlying objects were needed as a fundamental code construct that is used in almost all codebases. That's why the <a target="_blank" href="https://doc.rust-lang.org/std/boxed/struct.Box.html">Box&lt;T&gt;</a> type was provided.</p>
<h1 id="heading-comparision">Comparision</h1>
<p>As you already know, the <code>Box&lt;T&gt;</code> is a direct replacement for <code>std::unique_ptr&lt;T&gt;</code>. Let's start with a comparison</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td></td><td>Box&lt;T&gt;</td><td>std::unique_ptr&lt;T&gt;</td></tr>
</thead>
<tbody>
<tr>
<td>Movable</td><td>Yes</td><td>Yes</td></tr>
<tr>
<td>Copyable</td><td>No</td><td>No</td></tr>
<tr>
<td>Automatic memory deallocation</td><td>Yes</td><td>Yes</td></tr>
<tr>
<td>Constructable from previously allocated memory</td><td><a class="post-section-overview" href="#notes-unsafe">No<sup>1</sup></a></td><td>Yes</td></tr>
<tr>
<td>Can leak resources</td><td><a class="post-section-overview" href="#notes-unsafe">No<sup>1</sup></a></td><td>Yes</td></tr>
<tr>
<td>Allow in-place construction</td><td>No/Yes</td><td>Yes</td></tr>
<tr>
<td>Can be empty (aka nullptr)</td><td>No</td><td>Yes</td></tr>
</tbody>
</table>
</div><p>Let's have a detailed look at the above points</p>
<h2 id="heading-movability-and-copyability">Movability and Copyability</h2>
<p>In both languages, the compiler will make sure that once an object is created, you can have only one instance of it at a time. This is achieved by different means (in C++ by deleting copy &amp; assignment operators, in Rust by borrowing rules and not providing <a target="_blank" href="https://doc.rust-lang.org/std/marker/trait.Copy.html">Copy</a> trait).</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">auto</span> dynamicData = <span class="hljs-built_in">std</span>::make_unique&lt;Data&gt;();
    <span class="hljs-keyword">auto</span> newObject = dynamicData; <span class="hljs-comment">// ❌ Will not compile, missing copy constructor</span>

    <span class="hljs-keyword">auto</span> movedObject = <span class="hljs-built_in">std</span>::move(dynamicData);  <span class="hljs-comment">// ✅ All fine, the owned memory was moved into this instance</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>And equivalent in Rust</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Data</span></span> {
    some_field: <span class="hljs-built_in">i32</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> dynamic_data: <span class="hljs-built_in">Box</span>&lt;Data&gt; = <span class="hljs-built_in">Box</span>::new(Data { some_field: <span class="hljs-number">0</span> });
    <span class="hljs-keyword">let</span> new_object: <span class="hljs-built_in">Box</span>&lt;Data&gt; = dynamic_data; <span class="hljs-comment">// ✅ This is valid because ownership of the Box is moved to new_object</span>
    <span class="hljs-comment">// Copy cannot be made because Box does not implement the Copy trait</span>
    <span class="hljs-comment">// println!("{}", dynamic_data.some_field); // ❌ This would cause a compile-time error because dynamic_data has been moved to new_object</span>
}
</code></pre>
<h2 id="heading-automatic-memory-deallocation">Automatic memory deallocation</h2>
<p>As before, implementation, language, and compiler will ensure that once the object's lifetime is finished, the destructor (or <a target="_blank" href="https://doc.rust-lang.org/std/ops/trait.Drop.html">Drop</a> in Rust) will be called, which will then call destructor (or Drop) on held <code>T</code> and free the memory allocated by the system allocator.</p>
<p>The only subtle difference here is that <code>std::unique_ptr</code> supports custom deleters that can be part of the object instance and the type. This is currently not possible in stable Rust when using the plain <code>Box</code> type.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The custom allocator support for <code>Box</code> is already in nightly (<a target="_self" href="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.new_in">new_in</a>), so it will land in stable release in some time</div>
</div>

<h2 id="heading-constructable-from-previously-allocated-memory">Constructable from previously allocated memory</h2>
<p>In C++, <code>std::unique_ptr</code> lets us construct its instance from a previously created <code>T*</code>. Moreover, you can change the managed memory during its lifetime via the <code>.reset(T*)</code> method call. This opens up a whole bunch of checks that developers have to do to ensure that, after the creation of <code>std::unique_ptr</code>, the underlying memory is correct:</p>
<ul>
<li><p><code>nullptr</code> check on <code>T*</code> upon creation</p>
</li>
<li><p>ensure via external tooling or extensive reviews that <code>reset</code> is not called with <code>nullptr</code>, or each subsequent dereference has a <code>nullptr</code> check beforehand</p>
</li>
</ul>
<p>In the end, construction from a raw pointer is still dangerous because you also need to ensure that no one else has this pointer and will <strong>not attempt to release it</strong>. We can clearly see that even though C++ provided constructs that solve a lot of pointer issues for us, it's still error-prone, easy to misuse, and becomes tricky to catch in review or during the maintenance period as bugs emerge.</p>
<p>In Rust, the <code>Box</code> cannot be created from previously allocated <a class="post-section-overview" href="#notes-unsafe">memory<sup>1</sup></a>. <strong>That's it</strong>.</p>
<p><strong>So simple, so safe.</strong> <code>Box</code> will take care of allocation, take over the pointer, and hide it inside so you cannot misuse it. No <code>nullptr</code> checks, no hard-to-spot replacement of managed objects. You are fully covered.</p>
<p>Let’s head into an example</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Data</span> {</span>
  <span class="hljs-keyword">int32_t</span> someData;
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">auto</span> * instance = <span class="hljs-keyword">new</span> Data();
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span> &lt; Data &gt; ptr {
    instance
  };

  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; ptr -&gt; someData &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// ✅ All good for now</span>
  <span class="hljs-comment">// Some time later in code base</span>
  ptr.reset(); <span class="hljs-comment">// ❌ Next `ptr` dereference will be undefined behavior </span>
  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; ptr -&gt; someData &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// ❌ As above, will lead to crash or not - depends on compiler (try it in ccp.sh and godbolt)</span>

  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span> &lt; Data &gt; ptrOther {
    <span class="hljs-literal">nullptr</span>
  }; <span class="hljs-comment">// ❌ Same issue as after reset, `ptrOther` contains nullptr so dereferencing is undefined behavior </span>

  <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; ptrOther -&gt; someData &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>And equivalent in Rust</p>
<pre><code class="lang-rust"><span class="hljs-comment">// None of these errors can happen in Rust 🎊</span>
</code></pre>
<h2 id="heading-can-leak-resources">Can leak resources</h2>
<p>Using <code>std::unique_ptr</code>, one can leak resources by simply calling <code>release</code>. This gives back a pointer to the user (so now let's hope we remember to release it) and potentially leaves the instance with <code>nullptr</code>. So we are then in: <a class="post-section-overview" href="#can-be-empty">Can be empty</a></p>
<p><code>Box</code> does not allow <a class="post-section-overview" href="#notes-unsafe">a leak of the resource<sup>1</sup></a>. You can only obtain a reference to it. There is no way that we will end up with <strong>dangling pointers</strong>, <strong>unfreed memory</strong>, or anything else.</p>
<h2 id="heading-can-be-empty-aka-nullptr">Can be empty (aka <code>nullptr</code>)</h2>
<p>As in previous points, <code>std::unique_ptr</code> it can be constructed from any pointer, so it can be <code>nullptr</code> ! As mentioned, it is cumbersome to prove that once you are dereferencing data inside it, it is ensured that you are accessing the correct memory location.</p>
<p><strong>In Rust, you are covered</strong>. No way to have <code>nullptr</code> in <code>Box</code> or a wrong memory <a class="post-section-overview" href="#notes-unsafe">location<sup>1</sup></a>.</p>
<h1 id="heading-unsafe-rust">Unsafe Rust</h1>
<p>Everything that was written above for <code>Box</code> is true as long as you are using safe Rust. However, in practice, many of the mentioned operations, like releasing resources, are needed in complex implementations. That's why <code>Box</code> also provides a set of <code>unsafe</code> APIs, which are similar to <code>std::unique_ptr</code>. The core difference is that such usages have to be clearly annotated in code via <code>unsafe {}</code> blocks, which draw attention during reviews. Additionally, in practice, this is needed only by some libraries that are later used widely, so the majority of us will simply never need to use it, staying <strong>SAFE</strong> ☺️.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you are curious what more powers we get once we go to unsafe Rust, check it out <a target="_self" href="https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html">here</a></div>
</div>

<h1 id="heading-rust-extensions">Rust extensions</h1>
<p><code>Box</code> is a fundamental code unit in Rust. It's a built-in compiler implementation with additional guarantees that <code>std::unique_ptr</code> does not have. For example, <code>Box</code> is guaranteed to have the same memory footprint as <code>T*</code> with no overhead.</p>
<p>Additionally, <code>Box</code> provides a very powerful and robust API, well-integrated with custom and base types, allowing conversions, extraction, and other manipulations. One notable feature is the ability to provide an object API that depends on <code>self</code> being <code>Box</code>. This enables developers to model APIs that are only available for a given type once it's wrapped in <code>Box</code>.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Data</span></span> {
    some_field: <span class="hljs-built_in">i32</span>,
}

<span class="hljs-keyword">impl</span> Data {
    <span class="hljs-comment">/// This method is only available on `Box&lt;Data&gt;`</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">available_on_boxed</span></span>(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">Self</span>&gt;) -&gt; <span class="hljs-built_in">i32</span> {
        <span class="hljs-keyword">self</span>.some_field * <span class="hljs-number">3</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">square</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">i32</span> {
        <span class="hljs-keyword">self</span>.some_field * <span class="hljs-keyword">self</span>.some_field
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> dynamic_data: <span class="hljs-built_in">Box</span>&lt;Data&gt; = <span class="hljs-built_in">Box</span>::new(Data { some_field: <span class="hljs-number">4</span> });
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, dynamic_data.available_on_boxed());
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, dynamic_data.square());

    <span class="hljs-keyword">let</span> data: Data = Data { some_field: <span class="hljs-number">0</span> };
    <span class="hljs-comment">//  println!("{}", data.available_on_boxed()); // Will cause `no method named `available_on_boxed` found for struct `Data` in the current scope`</span>

    <span class="hljs-comment">// Some other integrations</span>
    <span class="hljs-keyword">let</span> vector_data = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">34</span>];
    <span class="hljs-keyword">let</span> boxed_vector_data: <span class="hljs-built_in">Box</span>&lt;[<span class="hljs-built_in">i32</span>]&gt; = vector_data.into_boxed_slice(); <span class="hljs-comment">// Vector to dynamically allocated array (aka boxed slice)</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, dynamic_data.some_field); <span class="hljs-comment">// Accessing field directly, without a need to dereference as Rust does it automatically (Box implementes Deref trait)</span>
}
</code></pre>
<p>Why would we need such feature at all?</p>
<p>Becasue it opens new, better possibilties to design API. One of examples could be a recursive patterns where You can change objects in between. Imagine a pseudo code:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">SomeRecursiveTrait</span></span> {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(<span class="hljs-keyword">self</span>: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">Self</span>&gt;) -&gt; <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> State&gt;;
}

...
<span class="hljs-keyword">impl</span> SomeRecursiveTrait <span class="hljs-keyword">for</span> NodeA {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(<span class="hljs-keyword">self</span>: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">Self</span>&gt;) -&gt; <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> SomeRecursiveTrait&gt; {
    <span class="hljs-built_in">Box</span>::new(NodeA ::new(<span class="hljs-keyword">self</span>.field1))
  }
}

<span class="hljs-keyword">impl</span> SomeRecursiveTrait <span class="hljs-keyword">for</span> NodeB {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(<span class="hljs-keyword">self</span>: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">Self</span>&gt;) -&gt; <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> SomeRecursiveTrait&gt; {
    <span class="hljs-built_in">Box</span>::new(NodeC::new(<span class="hljs-keyword">self</span>.field2))
  }
}
</code></pre>
<p>This allows implementor to:</p>
<ul>
<li><p>express that the object is consumed on each <code>next</code> call</p>
</li>
<li><p>Hide a real type returning <code>dyn SomeRecursiveTrait</code> and allow untyped abstraction and later use dynamic dispatch (via <code>dyn Trait</code> which will allow ie. storing it in containers like <code>Vec</code>)</p>
</li>
<li><p>Keeps the trait object safe (<code>Box&lt;dyn Trait&gt;</code> has known size at compile time so it’s <code>Sized</code>)</p>
</li>
</ul>
<h2 id="heading-placement-allocation">Placement allocation</h2>
<p>Unlike C++, where placement new (<code>new(ptr) T()</code>) is available, Rust does not have placement allocation concept (yet) in its implementation. This can cause some issues when one wants to create a big object on the heap. Consider this:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Clone, Copy)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SomeType</span></span> {
    value: <span class="hljs-built_in">u32</span>,
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BigData</span></span> {
    data: [SomeType; <span class="hljs-number">32000</span>],
}

<span class="hljs-keyword">impl</span> BigData {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        BigData {
            data: [SomeType { value: <span class="hljs-number">0</span> }; <span class="hljs-number">32000</span>],
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> instance = <span class="hljs-built_in">Box</span>::new(BigData::new());
}
</code></pre>
<p>What will happen is that first, we will create <code>BigData</code> instance on <code>the stack</code> , then, once <code>Box</code> allocates memory, this instance will be moved into heap memory. This will probably not cause more issues on <code>x86_64</code> targets with Unix OS, but once you try to run it in a more constrained environment like QNX on <code>aarch64</code>, it will likely cause <code>stackoverflow</code>. One of the solutions would be to increase the stack size for the particular thread where the instance is created, but this is probably not what the developer wants, as his data should be on the heap! Unfortunately, <strong>there is no out-of-the-box solution for this problem</strong>, however, proper use of <code>Box</code> API still enables that. Let’s have a look:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::mem::MaybeUninit;

<span class="hljs-meta">#[derive(Clone, Copy)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">SomeType</span></span> {
    value: <span class="hljs-built_in">u32</span>,
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BigData</span></span> {
    data: [SomeType; <span class="hljs-number">32000</span>],
}

<span class="hljs-keyword">impl</span> BigData {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        BigData {
            data: [SomeType { value: <span class="hljs-number">0</span> }; <span class="hljs-number">32000</span>],
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">placement_new</span></span>(<span class="hljs-keyword">mut</span> memory: <span class="hljs-built_in">Box</span>&lt;MaybeUninit&lt;BigData&gt;&gt;) -&gt; <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">Self</span>&gt; {
        <span class="hljs-keyword">unsafe</span> {
            <span class="hljs-comment">// !!!!!!</span>
            <span class="hljs-keyword">let</span> data_ptr: *<span class="hljs-keyword">mut</span> BigData = memory.as_mut_ptr(); <span class="hljs-comment">// (3)</span>
            <span class="hljs-keyword">let</span> first_elem: *<span class="hljs-keyword">mut</span> SomeType = &amp;raw <span class="hljs-keyword">mut</span> (*data_ptr).data <span class="hljs-keyword">as</span> *<span class="hljs-keyword">mut</span> SomeType;
            <span class="hljs-comment">// In this casem, we will use an equivalent of memcpy to initialize our type</span>
            std::ptr::write_bytes(first_elem, <span class="hljs-number">0xAB</span>, (*data_ptr).data.len()); <span class="hljs-comment">// (4)</span>

            memory.assume_init() <span class="hljs-comment">// (5)</span>
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> instance = <span class="hljs-built_in">Box</span>::new(BigData::new()); <span class="hljs-comment">// Uses stack memory</span>

    <span class="hljs-keyword">let</span> uninit_memory: <span class="hljs-built_in">Box</span>&lt;MaybeUninit&lt;BigData&gt;&gt; = <span class="hljs-built_in">Box</span>::new_uninit(); <span class="hljs-comment">// (1)</span>
    <span class="hljs-keyword">let</span> instance_no_stack: <span class="hljs-built_in">Box</span>&lt;BigData&gt; = BigData::placement_new(uninit_memory);
    <span class="hljs-comment">// (2)</span>
}
</code></pre>
<p>First, we create a <code>Box</code> that holds <code>uninitialized</code> memory (already allocated by system allocator) ready to accept our type <strong>(1)</strong>. The sharp eye will catch that now our type is not <code>Box</code>, but <code>Box&lt;MaybeUninit&gt;</code>. The explanation for <code>MaybeUninit</code> would require a new post in this series. You only need to know for now that this is a piece of memory that is not initialized yet, and developers need to initialize it before claiming it really is. Then, filling of the area with actual data has to be coded by us <strong>(2)</strong> ! Next, we obtain a pointer to the region <strong>(3)</strong>, fill it with our desired values <strong>(4),</strong> and then we claim that our data is ready to be used by <code>assume_init</code> <strong>(5)</strong>. This way, we never put a byte from a <code>BigData</code> onto the stack. Those manipulations, especially a pointer <code>derefernce</code> between points <strong>3</strong> and <strong>4,</strong> are inherently <code>unsafe</code>. That’s why they need to be wrapped into <code>unsafe</code> block. This will provide a clear indication to <code>reviewers</code> and <code>readers</code> that this piece of code in <code>placement_new</code> needs careful checking of all invariants to keep the rest of the code safe.</p>
<p>At the end, the purpose of this <code>unsafe</code> block is to allow certain manipulations of data, but also to check and remove all potential <code>unsafe</code> effects so that it can be used <strong>safely</strong> in the rest of the code base. This means that <code>Box&lt;Self&gt;</code> will still hold previous promises of <strong>not being null</strong>, being the only owner of allocated memory, or any other.</p>
<h1 id="heading-summary">Summary</h1>
<p>We have discussed the fundamental similarities and differences between <code>std::unique_ptr</code> and <code>Box</code>. As we can clearly see, thanks to the power of Rust, we can write the same low-level code as in C++, with the same overhead, while eliminating many <strong>fundamental problems during code development</strong>. This means that shipped code gains <strong>better quality</strong> immediately, takes <strong>less time</strong> to review, and <strong>does not introduce bugs</strong> that we would need to chase in production 😱.</p>
<p>Let me know what you think and what else you believe I should cover in this writing!</p>
<h6 id="heading-notes-unsafe">Notes unsafe</h6>
<p><strong>[1]</strong> - true, until using only safe Rust</p>
]]></content:encoded></item><item><title><![CDATA[Introduction]]></title><description><![CDATA[Warm welcome to you! 😊
I am really happy that You are checking out my series CPP to Rust developer journey 🦀💻.
The goal is to make a smooth transition into Rust for C++ developers, highlighting the similarities and differences between the language...]]></description><link>https://stacktofuture.com/introduction</link><guid isPermaLink="true">https://stacktofuture.com/introduction</guid><category><![CDATA[General Programming]]></category><category><![CDATA[Rust]]></category><category><![CDATA[C++]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Paweł Rutka]]></dc:creator><pubDate>Tue, 07 Oct 2025 17:55:05 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-warm-welcome-to-you"><strong>Warm welcome to you!</strong> 😊</h3>
<p>I am really happy that You are checking out my series <em>CPP to Rust developer journey</em> 🦀💻.</p>
<p>The goal is to make a <strong>smooth transition into Rust</strong> for C++ developers, highlighting the similarities and differences between the languages through specific well-known constructs and topics in C++.</p>
<h3 id="heading-key-points-for-all-articles-in-this-series">Key points for all articles in this series</h3>
<ul>
<li><p>Text is <strong>handwritten</strong> along with examples (no AI generation)</p>
</li>
<li><p>Articles in series are aiming to be technical and in-depth, allowing the reader structure their understanding and pave solid ground for self development</p>
</li>
<li><p>If there is <strong>AI-generated</strong> content, It will be flagged (most likely pictures, etc.)</p>
</li>
</ul>
<p>🚀 Let's dive together into the depths of Rust when approaching it as a C++ developer. Enjoy! 🦀✨</p>
]]></content:encoded></item></channel></rss>