Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use placement new. Like, set a maximal limit of size you want to allow <code>callback</code> to have, like <code>16</code> bytes. Then, put an <code>unsigned char</code> buffer into your <code>callback</code> class that's exactly that wide, and make sure it's aligned correctly (<code>GCC</code> has an attribute for that, and if you are lucky, microsoft has an attribute for that too). </p> <p>You may also go fairly safe if you use an union, and beside the char buffer put dummies of the types you want to stuff into it - that will ensure proper alignment too. </p> <p>Then, instead of using normal new, use placement new, like</p> <pre><code>if(placement_allocated&lt; callable_from_object&lt;C&gt; &gt;::value) { new ((void*)buffer.p) // union member p is the unsigned char buffer callable_from_object&lt;C&gt;(object, method); c = (callable*)buffer.p; } else { c = new callable_from_object&lt;C&gt;(object, method); } </code></pre> <p>Then, make the <code>c</code> member a pointer instead. You also need to set a flag so you remember whether you have to call delete in the destructor, or leave the placement buffer alone with explicitly calling the destructor. </p> <p>That's <em>basically</em> how <code>boost::function</code> does it. It, however, does a whole lot of other stuff to optimize allocation. It uses its own vtable mechanism to optimize space, and of course is very well tested. </p> <p>Of course, this is not exactly easy to do. But that seems to be the only thing to do about it. </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