Boost shared_ptr with overloaded new / delete allocation

I use boost shared_ptr with my own memory manager like this (stripped down example, I hope there are no errors in it):

class MemoryManager { public: /** Allocate some memory.*/ inline void* allocate(size_t nbytes) { return malloc(nbytes); } /** Remove memory agian.*/ inline void deallocate(void* p) { free(p); } }; MemoryManager globalMM; // New operators inline void* operator new(size_t nbytes, ogl2d::MemoryManagerImpl& mm) { return globalMM.allocate(nbytes); } // Corresponding delete operators inline void operator delete(void *p, ogl2d::MemoryManagerImpl& mm) { globalMM.deallocate(p); } /** Class for smart pointers, to ensure * correct deletion by the memory manger.*/ class Deleter { public: void operator()(void *p) { globalMM.deallocate(p); } }; 

And I use it like this:

 shared_ptr<Object>(new(globalMM) Object, Deleter); 

But now I understand. If shared_ptr removes my onject, it calls Deleter :: operator () and the objects are deleted. But the destructor is not called ...

How can i change this?

+4
source share
2 answers

Since the remote user must destroy the object:

 class Deleter { public: void operator()(Object *p) { p->~Object(); globalMM.deallocate(p); } }; 

Edit: I made a mistake in my doing, fixed

+7
source

You can explicitly call the destructor (which means that the Deleter is likely to get T * instead of void * ). Please note that the code you provided does not actually use the new / delete location, so my answer only makes sense for this specific example.

0
source

All Articles