2010-11-15 20 views
4

我使用升壓shared_ptr的,像這樣我自己的內存管理器(剝離下來的例子,我希望有中沒有任何錯誤):與超載放置新的動力的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()並刪除對象。但破壞者不會叫...

我該如何改變這種情況?

回答

7

由於缺失者應銷燬對象:

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

編輯:我錯在我刪除器,固定

0

您可以明確調用析構函數(這意味着Deleter應該可能會收到T *而不是void *)。請注意,您提供的代碼實際上並未使用展示位置新/刪除,因此我的回答僅對此特定示例有意義。