Manually constructing a trivial base class via placement-new : <p><em>Beware, we're skirting the dragon's lair.</em></p>

<p>Consider the following two classes:</p>

<pre><code>struct Base {
    std::string const *str;
};

struct Foo : Base {
    Foo() { std::cout &lt;&lt; *str &lt;&lt; "\n"; }
};
</code></pre>

<p>As you can see, I'm accessing an uninitialized pointer. Or am I?</p>

<p>Let's assume I'm only working with <code>Base</code> classes that are <a href="http://en.cppreference.com/w/cpp/types/is_trivial" rel="noreferrer">trivial</a>, nothing more than (potentially nested) bags of pointers.</p>

<pre><code>static_assert(std::is_trivial&lt;Base&gt;{}, "!");
</code></pre>

<p>I would like to construct <code>Foo</code> in three steps:</p>

<ol>
<li><p>Allocate raw storage for a <code>Foo</code></p></li>
<li><p>Initialize a suitably-placed <code>Base</code> subobject via placement-new</p></li>
<li><p>Construct <code>Foo</code> via placement-new.</p></li>
</ol>

<p>My implementation is as follows:</p>

<pre><code>std::unique_ptr&lt;Foo&gt; makeFooWithBase(std::string const &amp;str) {

    static_assert(std::is_trivial&lt;Base&gt;{}, "!");

    // (1)
    auto storage = std::make_unique&lt;
        std::aligned_storage_t&lt;sizeof(Foo), alignof(Foo)&gt;
    &gt;();

    Foo * const object = reinterpret_cast&lt;Foo *&gt;(storage.get());
    Base * const base = object;

    // (2)
    new (base) Base{&amp;str};

    // (3)
    new (object) Foo(); 

    storage.release();
    return std::unique_ptr&lt;Foo&gt;{object};
}
</code></pre>

<p>Since <code>Base</code> is trivial, my understanding is that:</p>

<ul>
<li><p>Skipping the trivial destructor of the <code>Base</code> constructed at <code>(2)</code> is fine;</p></li>
<li><p>The trivial default constructor of the <code>Base</code> subobject constructed as part of the <code>Foo</code> at <code>(3)</code> does nothing;</p></li>
</ul>

<p>And so <code>Foo</code> receives an initialized pointer, and all is well.</p>

<p>Of course, this is what happens in practice, even at -O3 (<a href="http://coliru.stacked-crooked.com/a/44ecfa3329cf6226" rel="noreferrer">see for yourself!</a>).<br>
But is it safe, or will the dragon snatch and eat me one day?</p>
