Note that there are some explanatory texts on larger screens.

plurals
  1. POMaintaining a std::set<boost::shared_ptr>
    text
    copied!<p>I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to preserve its existence. The obvious result of this is that there can be no anonymous objects, which will be by far the most common.</p> <p>At present, instances are managed using a <code>std::set&lt;Instance*, spatial_sort&gt;</code>, where <code>spatial_sort</code> is a functor that sorts instances by position, for rendering and collision detection. Instances are removed and re-inserted each frame using their current position as a hint, under the assumption that they're not likely to move a whole lot in a fiftieth of a second. If a <code>dead</code> flag is set in the instance, it is erased from the set. The <code>Instance</code> constructors and destructor invoke <code>insert(this)</code> and <code>erase(this)</code>, respectively.</p> <p>In order to allow anonymous instances, I want to change the set to a <code>std::set&lt;boost::shared_ptr&lt;Instance&gt;, spatial_sort&gt;</code>, which would allow <code>Instance</code> to share ownership of instances and preserve their existence until they destroy themselves. Unfortunately, because the calls to <code>insert()</code> need to be placed in the constructor, <code>shared_from_this()</code> won't work for obtaining a <code>shared_ptr</code> to the <code>Instance</code>. It doesn't matter at all that <code>Instance</code> happens to already inherit from <code>boost::enable_shared_from_this&lt;&gt;</code> via its base class.</p> <p>Can anyone recommend a suitable workaround?</p> <p><strong>Edit:</strong></p> <p>I did what I should have been doing in the first place, and split the behaviour of the <code>Instance</code> class into two classes: <code>Instance</code> and <code>Reference</code>. The expression <code>new SomeClass</code> in a script then returns a <code>Reference</code> to a new <code>Instance</code>. The <code>Instance</code> objects themselves are never managed using a <code>shared_ptr</code>, so they are responsible for committing suicide in response to a suitable event, e.g., end of animation, end of level, etc.</p> <p>Thanks for the help! Refactoring is as good a solution as any if it Just Works.</p>
 

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