Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost shared_ptr with overloaded placement new/delete

I am using 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 am using it like this:

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

But now I am realizing. If the shared_ptr deletes my onject, it calls Deleter::operator() and the objects gets deleted. But the destructor does not get called ...

How can I change this?

like image 776
Nathan Avatar asked Nov 15 '10 07:11

Nathan


1 Answers

Because deleter should destroy the object:

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

Edit: I was wrong in my deleter, fixed

like image 103
Artyom Avatar answered Oct 23 '22 00:10

Artyom