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

#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个对象。