Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to manage shared_ptr that points to internal data of already referenced object?
    primarykey
    data
    text
    <p>Suppose I have these classes:</p> <pre><code>struct Engine { int engine_data; }; struct Car { shared_ptr&lt;Engine&gt; engine; int car_data; }; </code></pre> <p>For performance reasons, I want to make them tightly packed in memory (but I don't want to lose the flexibility of the design). So, I can create a "packed" structure, and a factory that will transparently return a new B instance:</p> <pre><code>struct PackedCarAndEngine { Engine engine; Car car; }; shared_ptr&lt;Car&gt; new_Car() { shared_ptr&lt;PackedCarAndEngine&gt; packed = make_shared&lt;PackedCarAndEngine&gt;(); // uses aliasing shared_ptr constructor packed-&gt;car.engine = shared_ptr&lt;Engine&gt;(packed, &amp;packed-&gt;engine); // again shared_ptr&lt;Car&gt; car = shared_ptr&lt;Car&gt;(packed, &amp;packed-&gt;car); return car; } </code></pre> <p>The problem is that this "car" instance will never be destroyed, because it have a reference count of two. When it dies, it will have a reference count of one, forever. Do you know a better way to keep using the internal shared_ptr's (so that I can attribute an "unpacked" reference if I want), and still make this packed structure?</p> <p><strong>UPDATE</strong></p> <p>I could use a no-op deleter, but then it would be very dangerous if I decide to keep the <code>engine</code> but not the <code>car</code>:</p> <pre><code> // ... packed-&gt;car.engine = shared_ptr&lt;Engine&gt;(&amp;packed-&gt;engine, do_nothing_deleter); // ... shared_ptr&lt;Car&gt; my_car = new_Car(); shared_ptr&lt;Engine&gt; my_engine = my_car-&gt;engine; my_car.reset(); // Danger: engine was destroyed here!!! cout &lt;&lt; my_engine-&gt;engine_data; // Crash! </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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