Nat*_*han 5 c++ memory-management placement-new shared-ptr
我正在使用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);
}
};
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
shared_ptr<Object>(new(globalMM) Object, Deleter);
Run Code Online (Sandbox Code Playgroud)
但现在我意识到了.如果shared_ptr删除了我的onject,它会调用Deleter :: operator()并删除对象.但析构函数不会被调用...
我怎么能改变这个?
因为删除器应该销毁对象:
class Deleter
{
public:
void operator()(Object *p) {
p->~Object();
globalMM.deallocate(p);
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:我的删除中错了,修复了
| 归档时间: |
|
| 查看次数: |
1284 次 |
| 最近记录: |