Item 36. Class-Specific Memory Management

类别:编程语言 点击:0 评论:0 推荐:

Item 36. Class-Specific Memory Management

在类中声明operator new 和 operator delete 成员就可以实现类自己的内存分配与管理。
class Handle {
  public:
    //...
    void *operator new( size_t );
    void operator delete( void * );
    //...
};
//...
Handle *h = new Handle; // uses Handle::operator new
//...
delete h; // uses Handle::operator delete

这样对于Handle的子类需要重载operator new 和 operator delete

class MyHandle : public Handle {
    //...
    void *operator new( size_t );
    void operator delete( void *, size_t ); // note 2nd arg
    //...
};
//...
Handle *h = new MyHandle; // uses MyHandle::operator new
//...
delete h; // uses MyHandle::operator delete

------------------------------------------------------
一个误解的概念:使用new和delete意味着使用heap内存
对于全局的那个operator new 和 operator delete,事实确实如此。既然operator new 和 operator

delete 都可以自定义,因此operator new 分配的内存就可以来自heap,静态分配的内存块,标准的容

器等。如下例所示:
struct rep {
    enum { max = 1000 };
    static rep *free; // head of freelist
    static int num_used; // number of slots used
    union {
        char store[sizeof(Handle)];
        rep *next;
    };
};
static rep mem[ rep::max ]; // block of static storage
void *Handle::operator new( size_t ) {
    if( rep::free ) { // if something on freelist
        rep *tmp = rep::free; // take from freelist
        rep::free = rep::free->next;
        return tmp;
    }
    else if( rep::num_used < rep::max ) // if slots left
        return &mem[ rep::num_used++ ]; // return unused slot
    else // otherwise, we're...
        throw std::bad_alloc(); // ...out of memory!
}
void Handle::operator delete( void *p ) { // add to freelist
    static_cast<rep *>(p)->next = rep::free;
    rep::free = static_cast<rep *>(p);
}


本文地址:http://com.8s8s.com/it/it22350.htm