• 静态存储区中创建动态对象


    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Test
    {
    private:
        static const unsigned int COUNT = 4;
        static char c_buffer[]; //首先定义一个静态存储区
            static char c_map[];
        int m_value;
    public:
    
        void* operator new(unsigned int size)
        {
            void* ret = NULL;
    
            //利用for循环查找在c_buffer这片空间中哪些是空闲的,可以用于创建一个Test对象。
            //遍历COUNT个位置,看每个位置有没有对象存在,如果没有对象存在,那么就可以返回这片内存空间。并且在这片内存空间中调用构造函数创建对象。
              for(int i=0; i<COUNT; i++)
          {
                if(!c_map[i])
                {
                    //表示当前的内存空间是可以用的
                         c_map[i] = 1;
                    ret = c_buffer + i * sizeof(Test);//做一个指针运算,用来查找c_buffer这块区域的可用空间的首地址
                         cout << "succeed to allocate memory: " << ret << endl;
    
                    break;
                }
            }
    
            return ret;
        }
    
        void operator delete(void* p)
        {
            if( p != NULL)
            {
                char* mem = reinterpret_cast<char*>(p);
                int index = (mem-c_buffer) / sizeof(Test);
                int flag = (mem-c_buffer) % sizeof(Test);
    
                if((flag == 0) && (0 <= index) && (index < COUNT))
                {
                    c_map[index] = 0;
                    cout << "succeed to free memory: " << p <<endl;
                }
            }
        }
    };
    //既然是静态的数组,需要在类外分配空间
    char Test::c_buffer[sizeof(Test) * Test::COUNT] = {0}; //定义一块静态的内存空间,这块内存空间中想要存储的就是Test对象,最多就可以存储4个Test对象。
    char Test::c_map[COUNT] = {0}; //用来标记在哪些位置已经创建了对象。
    
    int main()
    {
       cout << "====== Test Single Object ======" << endl;
       Test* pt = new Test;
       delete pt;
    
       cout << "====== Test Object Array ======" << endl;
       Test* pa[5] = {0};
    
       for(int i=0; i<5; i++)
       {
            pa[i] = new Test;
            cout << "pa[" << i << "] = " << pa[i] << endl;
       }
    
       for(int i=0; i<5; i++)
       {
            cout << " delete" << pa[i] << endl;
            delete pa[i];
       }
    
        return 0;
    }

     这个例子的精妙之处就是控制对象的产生的数目,就像该例中,只能产生4个对象。

  • 相关阅读:
    win10系统安装oracle11g时遇到INS-13001环境不满足最低要求
    C#文件重命名的代码
    自学MVC开发基础
    我的面试感悟-----3年工作经验的女程序员的感慨
    问心无愧,莫问前程
    Install your Application into RaspberryPi2 and automatically start up
    基于Vmware player的Windows 10 IoT core + RaspberryPi2安装部署
    MVC开发-后台开发总结
    页面长按禁止弹出选择菜单
    js检测链接(URL)是否有效
  • 原文地址:https://www.cnblogs.com/-glb/p/12296402.html
Copyright © 2020-2023  润新知