前言:经过改善单例类模板,再通过内存管理实现的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约定不重载。