c语言的malloc或者heapAlloc怎么实现new的这种功能?
比如现在有一个类,
class test{
public:
test():var1(2),var2(3)
{
}
int var1,var2;
};
template<typename T>
T * alloc_object()
{
T * result = malloc(sizeof(T));
new (T)result;
return result;
}
template<typename T, typename P1>
T * alloc_object(P1 const & p1 )
{
T * result = malloc(sizeof(T));
new (T)result(p1);
return result;
}
template<typename T, typename P1, typename P2>
T * alloc_object(P1 const & p1, P2 const & p2 )
{
T * result = malloc(sizeof(T));
new (T)result(p1,p2);
return result;
}
...
调用时:
int * x = alloc_object<int>(); //x = new int;
int * y = alloc_object<int>( 5 ); //y = new int(5);
complex a = alloc_object<complex>( 3, 4) //a = new complex(3,4);
class base_class
{
public:
void * operator new( size_t size )
{
return malloc(size);//可以换成自己的内存分配函数
}
void operator delete( void * p, size_t size )
{
free(p);//可以换成自己的内存分配函数
}
};