5

我正在将 boost shared_ptr 与我自己的内存管理器一起使用(精简示例,我希望其中没有错误):

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);
}
};

我正在这样使用它:

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

但现在我意识到了。如果 shared_ptr 删除了我的 onject,它会调用 Deleter::operator() 并且对象被删除。但是析构函数没有被调用......

我怎样才能改变这个?

4

2 回答 2

8

因为删除器应该销毁对象:

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

编辑:我的删除器错了,已修复

于 2010-11-15T07:35:14.857 回答
0

您可以显式调用析构函数(这意味着Deleter应该接收 aT *而不是 a void *)。请注意,您提供的代码实际上并未使用placement new/delete,因此我的回答仅对这个特定示例有意义。

于 2010-11-15T07:34:26.390 回答