Fast approach to wrapping data in a struct/class
<p><strong>EDIT:</strong> <em>The main intent is to allow manipulating underlying data as part of an encapsulated struct as opposed to direct data manipulation.</em></p>

<p>Which of the following approaches is recommended when it comes to wrapping some data inside a struct:</p>

<ol>
<li><p>Keep a pointer to the data within the struct:</p>

<p><code>new s(buf)</code>, which stores buf in a local field (<code>s-&gt;buf = buf</code>)</p></li>
<li><p>reinterpret_cast-ing a memory address to a struct:</p>

<p><code>reinterpret_cast&lt;s*&gt;(buf)</code></p></li>
<li><p>Use the <code>new</code> operator against the memory address where the data is located:</p>

<p><code>new(buf) s;</code></p></li>
</ol>

<p>Here is a sample program for these approaches:</p>

<pre><code>#include &lt;iostream&gt;
using namespace std;

struct s {
    int* i;
    s(int* buf) : i(buf) {}
    int getValue() { return *i * 2; }
};

struct s2 {
    int i;
    int getValue() { return i * 2; }
};

int main() {
    int buf = 10;
    s a(&amp;buf);
    cout &lt;&lt; "value: " &lt;&lt; a.getValue() &lt;&lt; ", size: " &lt;&lt; sizeof(a) &lt;&lt; ", address: " &lt;&lt; &amp;a &lt;&lt; ", buf-address: " &lt;&lt; &amp;buf &lt;&lt; endl;

    s2* a2 = new(&amp;buf) s2;
    cout &lt;&lt; "value: " &lt;&lt; a2-&gt;getValue() &lt;&lt; ", size: " &lt;&lt; sizeof(*a2) &lt;&lt; ", address: " &lt;&lt; a2 &lt;&lt; ", buf-address: " &lt;&lt; &amp;buf &lt;&lt; endl;

    s2* a3 = reinterpret_cast&lt;s2*&gt;(&amp;buf);
    cout &lt;&lt; "value: " &lt;&lt; a3-&gt;getValue() &lt;&lt; ", size: " &lt;&lt; sizeof(*a3) &lt;&lt; ", address: " &lt;&lt; a3 &lt;&lt; ", buf-address: " &lt;&lt; &amp;buf &lt;&lt; endl;
}
</code></pre>

<p>And the output:</p>

<pre><code>value: 20, size: 4, address: 0027F958, buf-address: 0027F964
value: 20, size: 4, address: 0027F964, buf-address: 0027F964
value: 20, size: 4, address: 0027F964, buf-address: 0027F964
</code></pre>

<p>Both size &amp; time are important. Also, maintainability is important, e.g. someone might add by mistake a virtual function to <code>s2</code> (which will mess up the data alignment).</p>

<p>Thanks!</p>
