Nathan
Nathan

Reputation: 7709

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?

Upvotes: 5

Views: 1346

Answers (2)

icecrime
icecrime

Reputation: 76755

You can explicitly call the destructor (which means that the Deleter should probably receive a T * instead of a void *). Note that the code you provided doesn't actually use placement new/delete, so my answer is only meaningful for this particular example.

Upvotes: 0

Artyom
Artyom

Reputation: 31233

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

Upvotes: 8

Related Questions