• Item 36. ClassSpecific Memory Management


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


  • 相关阅读:
    重构:以Java POI 导出EXCEL为例
    从源码角度看LinkedList一些基本操作(jdk1.7)
    OpenCV学习笔记(1)
    尝试实现手势控制计算机(持续跟进)
    神经网络学习笔记三——梯度检验、高级优化
    神经网络学习笔记二——反向传导
    神经网络学习笔记一——Neural Network
    C++ 指针和引用 吐血整理 Pointer&Reference
    BST 解析 (二)height and deletion
    BST 解析 (一)
  • 原文地址:https://www.cnblogs.com/aiwz/p/6333212.html
Copyright © 2020-2023  润新知