当前位置:首页 > 学习英语 > 专业英语 > 计算机英语>正文

c语言new的用法

【计算机英语】 2016-03-20本文已影响
C语言中new有三种使用方式:plain new,nothrow new和placement new:下面小编就和大家细说这三种用法分别是什么。  c语言new的用法:  一. 简介  。  (1)plain new顾名思义就是普通的new,就是我们惯常使用的new。在C++中是这样定义的:  void* operator new(std::size_t) throw(std::bad_alloc);  void operator delete(void *) throw();  提示:plain new在分配失败的情况下,抛出异常std::bad_alloc而不是返回NULL,因此通过判断返回值是否为NULL是徒劳的。  (2)nothrow new是不抛出异常的运算符new的形式。nothrow new在失败时,返回NULL。定义如下:  void * operator new(std::size_t,const std::nothrow_t&) throw();  void operator delete(void*) throw();  (3)placement new意即“放置”,这种new允许在一块已经分配成功的内存上重新构造对象或对象数组。placement new不用担心内存分配失败,因为它根本不分配内存,它做的唯一一件事情就是调用对象的构造函数。定义如下:  void* operator new(size_t,void*);  void operator delete(void*,void*);  提示1:palcement new的主要用途就是反复使用一块较大的动态分配的内存来构造不同类型的对象或者他们的数组。  提示2:placement new构造起来的对象或其数组,要显示的调用他们的析构函数来销毁,千万不要使用delete。  char* p = new(nothrow) char[100];  long *q1 = new(p) long(100);  int *q2 = new(p) int[100/sizeof(int)];  二.实例  1.plain new/delete.普通的new  定义如下:  void *operator new(std::size_t) throw(std::bad_alloc);  void operator delete(void*) throw();  注:标准C++ plain new失败后抛出标准异常std::bad_alloc而非返回NULL,因此检查返回值是否为NULL判断分配是否成功是徒劳的。  测试程序:  复制代码 代码如下:  #include "stdafx.h"  #include   using namespace std;  char *GetMemory(unsigned long size)  {  char *p=new char[size];//分配失败,不是返回NULL  return p;  }  int main()  {  try  {  char *p=GetMemory(10e11);// 分配失败抛出异常std::bad_alloc  //...........  if(!p)//徒劳  cout<<"failure"<  #include   using namespace std;  char *GetMemory(unsigned long size)  {  char *p=new(nothrow) char[size];//分配失败,是返回NULL  if(NULL==p)  cout<<"alloc failure!"<  #include   using namespace std;  class ADT  {  int i;  int j;  public:  ADT()  {  }  ~ADT()  {  }  };  int main()  {  char *p=new(nothrow) char[sizeof(ADT)+2];  if(p==NULL)  cout<<"failure"<ADT::~ADT();//显示调用析构函数  delete []p;  return 0;  }  注:使用placement new构造起来的对象或数组,要显式调用它们的析构函数来销毁(析构函数并不释放对象的内存),千万不要使用delete.这是因为placement new构造起来的对象或数组大小并不一定等于原来分配的内存大小,使用delete会造成内存泄漏或者之后释放内存时出现运行时错误。
网友评论

Copyright © 2019 All Rights Reserved

错不了学习网 版权所有

回到顶部