随笔 - 56, 文章 - 0, 评论 - 0, 引用 - 0
数据加载中……

重载全局运算符new与delete

一、
读程序:
#include<stdio.h>
#include
<malloc.h>
void* operator new(unsigned bytes)
{
    printf(
"SELF-GLOBAL-operator new!bytes=%d\n",bytes);
    
void* pvTemp=malloc(bytes);
    
return pvTemp;
}

void operator delete(void *pvMem)
{
    printf(
"SELF-GLOBAL-operator delete\n");
    free(pvMem);
}

class claA
{
    
int dat[5];
    
public:
    claA()
    
{
        printf(
"claA::claA()!\n");
    }

    
~claA()
    
{
        printf(
"claA::~claA()!\n");
    }

}
;
int main()
{
    
int *pi=new int(123);
    delete pi;
    claA 
*pmyCla=new claA;
    delete pmyCla;
    claA
* pmyClaA=new claA[2];
    delete []pmyClaA;
    
return 0;
}


输出结果为:
SELF-GLOBAL-operator new!bytes=4
SELF
-GLOBAL-operator delete
SELF
-GLOBAL-operator new!bytes=20
claA::claA()
!
claA::
~claA()!
SELF
-GLOBAL-operator delete
SELF
-GLOBAL-operator new!bytes=44
claA::claA()
!
claA::claA()
!
claA::
~claA()!
claA::
~claA()!
SELF
-GLOBAL-operator delete

二、
读程序:
#include<stdio.h>
#include
<string.h>
#include
<process.h>

#define MAX_SIZE 10000
static char MemArea[MAX_SIZE];
static char*pm=MemArea;

void* operator new(unsigned bytes)
{
    printf(
"SELF-GLOBAL-operator new!bytes=%d\n",bytes);
    
if(pm+bytes<=MemArea+MAX_SIZE)
    
{
        pm
+=bytes;
        
return (void*)(pm-bytes);
    }

    
else
    
{
        printf(
"My-new-fail!I only have %d bytes memory now!",MemArea+MAX_SIZE-pm);
        printf(
" but you need %d bytes~\n",bytes);
        
return NULL;
    }

}

void operator delete(void *pvMem)
{
    printf(
"SELF-GLOBAL-operator delete!\n");
    
if((char*)pvMem>=MemArea&&(char*)pvMem<MemArea+MAX_SIZE)
    pm
=(char*)pvMem;
}

int main()
{
    
char *pc=(char*)new char[MAX_SIZE];
    strcpy(pc,
"1234567abcdefg");
    printf(
"pc=>%s\n",pc);
    delete pc;
    
double *pd=(double*)new double(862.13);
    printf(
"%d\n",sizeof(double));
    printf(
"(*pd)=%f\n",*pd);
    
double* pdA1=(double*)new double[10];
    delete[]pdA1;
    
double* pdA2=(double*)new double[1250];
    
if(!pdA2)
    
{
        delete pd;
    }

    delete[]pdA2;
    delete pd;
    
return 0;
}

输出结果为:
SELF-GLOBAL-operator new!bytes=10000
pc
=>1234567abcdefg
SELF
-GLOBAL-operator delete!
SELF
-GLOBAL-operator new!bytes=8
8
(
*pd)=862.130000
SELF
-GLOBAL-operator new!bytes=80
SELF
-GLOBAL-operator delete!
SELF
-GLOBAL-operator new!bytes=10000
My
-new-fail!I only have %d bytes memory now! but you need 9992 bytes~
SELF
-GLOBAL-operator delete!
SELF
-GLOBAL-operator delete!

posted on 2009-08-22 18:22 八路 阅读(573) 评论(0)  编辑 收藏 引用 所属分类: 学习笔记


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理