Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding operator new/delete in derived class
    text
    copied!<p>I have a stateless, abstract base class from which various concrete classes inherit. Some of these derived classes are stateless as well. Because many of them are created during a run, I'd like to save memory and overhead by having all stateless derived classes emulate a singleton, by overriding operator new()/delete(). A simplified example would look something like this:</p> <pre><code>#include &lt;memory&gt; struct Base { virtual ~Base() {} protected: Base() {} // prevent concrete Base objects }; struct D1 : public Base { // stateful object--default behavior int dummy; }; struct D2 : public Base { // stateless object--don't allocate memory void* operator new(size_t size) { static D2 d2; return &amp;d2; } void operator delete(void *p) {} }; int main() { Base* p1 = new D1(); Base* p2 = new D1(); Base* s1 = new D2(); Base* s2 = new D2(); delete p1; delete p2; delete s1; delete s2; return 0; } </code></pre> <p>This example doesn't work: <code>delete s2;</code> fails because <code>delete s1;</code> called <code>~Base()</code>, which deallocated the shared <code>Base</code> in <code>d2</code>. This can be addressed by adding the same trick with new/delete overloading to Base. But I'm not sure this is the cleanest solution, or even a correct one (valgrind doesn't complain, FWIW). I'd appreciate advice or critique.</p> <p>edit: actually, the situation is worse. The Base class in this example isn't abstract, as I claimed. If it's made abstract, through the addition of a pure virtual method, then I can no longer apply the new/delete overriding trick, because I cannot have a static variable of type Base. So I don't have any solution for this problem!</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