细说C++中的new与delete

发表于:2014-3-05 10:02

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Tyrion-Lannister    来源:51Testing软件测试网采编

  (2) delete opeartor
  [::] delete cast-expression
  [::] delete [ ] cast-expression
  上面是delete operator的原型,第一种用来释放普通的对象(包括内建类型)类型的内存,第二种用来释放对象的数组类型的内存。在C++中,用new operator分配的动态内存,必须调用delete operator来释放,通常用delete operator释放内存编译器要做下面两项工作:
  a. 调用对象析构函数来析构对象
  b. 调用operator delete function来释放内存(deallocate the memory)
  3. 关于new/delete使用过程中一些需要注意的点
  (1)如何区别operator new/delete function 与 new/delete operator ?
  通过上面的讲述,不难看出,我们分配/释放动态内存,调用的是new/delete operator, 而在调用new/delete的过程中,编译器会自动调用operator new/delete function来完成实际的内存分配/释放的工作
  (2) 用delete operator去释放一块不是由new operator释放的内存,结果是不可预料的,因此,切记,operator new与operator delete一定要配对使用,这是写好程序的基础
  (3) new operator调用失败会抛出std::bad_alloc异常,前提是你没有自己重载对应的operator new function;delete operator失败,常见的原因是多次delete同一块内存
  (4) 如果一块内存被delete后,再对它解引用(Dereference),结果也是不可预测的,很可能导致程序崩溃
  (5) delete一个空(NULL)指针是安全的,没有任何害处的
  (6) 类成员类型的operator new/delete函数必须为静态(static)函数,因此它们不能为虚函数(virtual function),也遵守public, protected, private的访问权限控制
  4. 关于上面所讲的内容的一些例子:
  程序:
#include <stdio .h>
#include <stdlib .h>
void * operator new(size_t unSize)
{
printf("operator new called\n");
return malloc(unSize);
}
void * operator new(size_t unSize, int nLine, const char * pFunc)
{
printf("operator new called, line: %d, func: %s\n",
nLine, pFunc);
return malloc(unSize);
}
void operator delete(void * pMem)
{
printf("delete1\n");
free(pMem);
}
class A
{
public:
A(int a = 0) :
_a(a)
{
printf("constructor called\n");
}
{
printf("~A()\n");
}
static void operator delete(void * pMem, size_t unSize)
{
printf("delete2: %u\n", unSize);
free(pMem);
}
private:
int _a;
};
class B: public A
{
public:
~B()
{
printf("~B()\n");
}
int _b;
int _bb;
};
int main()
{
A * pA = new A(10);
printf("#######\n");
A * pB = new (__LINE__, __func__) B();
printf("#######\n");
A * szA = new A[10];
printf("#######\n");
delete pA;
printf("#######\n");
delete pB;
printf("#######\n");
delete [] szA;
printf("#######\n");
char * pC = NULL;
delete pC;
}
32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号