C++ 笔记:N例类模板+内存管理

前言:经过改善单例类模板,再通过内存管理实现的N例类模板,测试没有问题,功能算是达标,实际项目工程使用有待考究。

#include <string>
#include <iostream>
#include <cstdlib>

using namespace std;

//N例类模板
template
< typename T >
class Singleton
{
    static const unsigned int c_count = 3;
    static char c_buffer[];
    static char c_map[];

    static T* c_singleton;
public:
    Singleton()
    {

    }

    static T* GetInstance()
    {   
        void* ret = NULL;
        for(int i=0; i<c_count; i++)
        {
            if( !c_map[i] )
            {   
                c_map[i] = 1;

                ret = c_buffer + i * sizeof(T);

                cout << "succeed to allocate memory: " << ret << endl;

                break;
            }
        }

        return static_cast<T*>(ret);
    }

    static void delete_Instance(void *p)
    {
    if( p != NULL )
        {
            char* mem = reinterpret_cast<char*>(p);
            int index = (mem - c_buffer) / sizeof(T);
            int flag = (mem - c_buffer) % sizeof(T);

            if( (flag == 0) && (0 <= index) && (index < c_count) )
            {
                c_map[index] = 0;

                cout << "succeed to free memory: " << p << endl;
            }
        }
    }

};

template
< typename T >
char Singleton<T>::c_buffer[sizeof(T) * Singleton<T>::c_count] = {0};

template
< typename T >
char Singleton<T>::c_map[Singleton<T>::c_count] = {0};

//测试类
class Test
{
    int value;
public:
    Test()
    {
        value = 90;
    }
      void print()
    {
        cout << "i'm here " << value <<  endl;
    }

    void operator delete(void *p)
    {
        Singleton<Test>::delete_Instance(p);  
    }

};

int main()
{
    //Singleton<Test>* test = new Singleton<Test>;
    Test* test[3];
    for(int i = 0 ; i<3;i++)
    {
        test[i] = Singleton<Test>::GetInstance();
        test[i]->print();
        cout << test[i] << " This is " << i << endl;    
    }

    cout << "==========Gorgeous dividing line==========" << endl;

    for(int i = 0; i < 3 ; i++)
    {
        cout << "delete " << test[i] << endl;
        delete test[i];
    }

    return 0;
}

输出结果如下:
这里写图片描述

总结:在C++中重载new操作符如果不调用构造函数,成员变量在new时将为默认初始值;进一步理解为,构造函数在new时进行调用,进而构造函数一般是public,而不是private,所以一般只重载局部new,全局new约定不重载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值