Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is do-able with proper use of the <code>weak_ptr</code> class. In fact, you are already quite close to having a good solution. You are right that you cannot be expected to "out-think" your client programmers, nor should you expect that they will always follow the "rules" of your API (as I'm sure you are already aware). So, the best you can really do is damage control.</p> <p>I recommend having your call to <code>GetSubsystem</code> return a <code>weak_ptr</code> rather than a <code>shared_ptr</code> simply so that the client developer can test the validity of the pointer without always claiming a reference to it.</p> <p>Similarly, have <code>pParentSystem</code> be a <code>boost::weak_ptr&lt;System&gt;</code> so that it can internally detect whether its parent <code>System</code> still exists via a call to <code>lock</code> on <code>pParentSystem</code> along with a check for <code>NULL</code> (a raw pointer won't tell you this).</p> <p>Assuming you change your <code>Subsystem</code> class to always check whether or not its corresponding <code>System</code> object exists, you can ensure that if the client programmer attempts to use the <code>Subsystem</code> object outside of the intended scope that an error will result (that you control), rather than an inexplicable exception (that you must trust the client programmer to catch/properly handle).</p> <p>So, in your example with <code>main()</code>, things won't go BOOM! The most graceful way to handle this in the <code>Subsystem</code>'s dtor would be to have it look something like this:</p> <pre><code>class Subsystem { ... ~Subsystem() { boost::shared_ptr&lt;System&gt; my_system(pParentSystem.lock()); if (NULL != my_system.get()) { // only works if pParentSystem refers to a valid System object // now you are guaranteed this will work, since a reference is held to the System object my_system-&gt;LogMessage( "Destroying..." ); } // Destroy this subsystem: deallocate memory, release resource, etc. // when my_system goes out of scope, this may cause the associated System object to be destroyed as well (if it holds the last reference) } ... }; </code></pre> <p>I hope this helps!</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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