Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I ended up creating the following class:</p> <pre><code>#include &lt;type_traits&gt; // Or &lt;boost/type_traits.hpp&gt; template &lt;typename Ty&gt; class manually_constructed { public: template &lt;typename T&gt; manually_constructed(T construct_func) { construct_func(static_cast&lt;Ty*&gt;(static_cast&lt;void*&gt;(&amp;data))); } ~manually_constructed() { static_cast&lt;Ty*&gt;(static_cast&lt;void*&gt;(&amp;data))-&gt;~Ty(); } Ty&amp; operator*() { return *static_cast&lt;Ty*&gt;(static_cast&lt;void*&gt;(&amp;data)); } Ty* operator-&gt;() { return static_cast&lt;Ty*&gt;(static_cast&lt;void*&gt;(&amp;data)); } private: // Replace 'std' with 'boost' if your standard library doesn't support // type_traits, yet. std::aligned_storage&lt;sizeof(Ty), std::alignment_of&lt;Ty&gt;::value&gt;::type data; }; </code></pre> <p>Then, in my class, I can have a member such as <code>manually_constructed&lt;OtherClass&gt; object</code> and a private static method such as:</p> <pre><code>static void construct_object(OtherClass *p) { try { new(p) OtherClass(/* Risky arguments */); } catch(...) { new(p) OtherClass(/* Fallback arguments */); } } </code></pre> <p>Finally, in my initializer list, I can have <code>object(construct_object)</code>.</p> <p>With this solution, all member objects are stored within the containing object, there is no additional space overhead, all member objects are constructed in the correct order, and manually constructed objects will be destructed automatically.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload