Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have a look at this article: <a href="http://www.bearcave.com/software/c++_mem.html" rel="nofollow noreferrer">Overloading New in C++ </a>. You could overload the <code>new</code> operator for <code>ObjectBase</code> so that it takes your allocator as a parameter and does the rest of the job:</p> <pre><code>void *ObjectBase::operator new(size_t size, Allocator *allocator) { void *ptr = allocator-&gt;allocate(size); // Hack to pre-initialize member before constructor is called ObjectBase *obj = static_cast&lt;ObjectBase *&gt;(ptr); obj-&gt;setAllocator(allocator); return ptr; } </code></pre> <p>Normally, the operator is supposed to just return a pointer to the allocated memory, but since you need access to the new object to call your <code>setAllocator</code> method, I've included a hack that should (but may not) work. Note that the actual <code>ObjectBase</code> constructor is called after the above function returns, so you should make sure that your constructor does not re-initialize the allocator member.</p> <p>And then a similar overload for <code>delete</code>:</p> <pre><code>void ObjectBase::operator delete(void *ptr) { ObjectBase *obj = static_cast&lt;ObjectBase *&gt;(ptr); obj-&gt;getAllocator()-&gt;free(ptr); } </code></pre> <p>You would then create objects by calling <code>new (allocator) SomeClass(...)</code> where <code>SomeClass</code> derives from <code>ObjectBase</code>.</p> <p><strong>Edit:</strong> One potential problem with this is that you cannot allocate objects on the stack any more, because there is no way to initialize the allocator to <code>NULL</code> without affecting the how the overloaded <code>new</code> works.</p> <p><strong>Update:</strong> There is one last (dirty) hack to get it working with both stack and dynamic allocation. You can make <code>new</code> set a global variable (a class static member would work as well) pointing to the current allocator and the constructor could consume this and reset it to <code>NULL</code>. At all other times, this global will already be <code>NULL</code> so an object constructed on the stack will get a <code>NULL</code> allocator.</p> <pre><code>Allocator *currentAllocator = NULL; void *ObjectBase::operator new(size_t size, Allocator *allocator) { currentAllocator = allocator; return allocator-&gt;allocate(size); } ObjectBase::ObjectBase() { setAllocator(currentAllocator); currentAllocator = NULL; } </code></pre>
 

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