C++ new运算符误用之详解
来源:互联网 发布:出国旅游英语翻译软件 编辑:程序博客网 时间:2024/05/22 05:09
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判断分配内存空间是没有意义的
普通new申请空间示例代码:
#include <iostream>using namespace std;typedef unsigned long ULONGS;char *GetMemory(ULONGS size);int main(){try{ULONGS ulSize(10e11);char *pMem=GetMemory(ulSize);if(NULL == pMem){cout<<"Alloc Memory failure!"<<endl;}delete [] pMem;pMem = NULL;}catch(const std::bad_alloc &ex){cout<<ex.what()<<endl;}return 0;}char *GetMemory(ULONGS size){char * pMem = new char[size];//分配失败,指针不为空if(NULL == pMem){cout<<"Alloc Memory failure!"<<endl;}return pMem;}
这段代码运行出来结果如下图所示:
代码抛出申请申请空间异常的信息
2.nothrow new/delete:
void *operator new(std::size_t,const std::nothrow_t&) throw();
void operator delete(void*) throw();
struct nothrow_t{}; const nothrow_t nothrow;//nothrow作为new的标志性
将上面的代码中申请内存空间函数稍作如下修改,其余函数调用都不变
char *GetMemory(ULONGS size){char * pMem = new(nothrow) char[size];//分配失败,指针为空if(NULL == pMem){cout<<"Alloc Memory failure!"<<endl;}return pMem;}
运行该段程序,则运行结果显示申请空间失败后指针为空,运行结果如下所示:
0 0
- C++ new运算符误用之详解
- C++:new运算符和new表达式详解
- C++学习之new返回值的误用-new(nothrow)
- C语言memset函数详解与误用
- C语言memset函数详解与误用
- C#_is运算符,new运算符,typeof运算符
- C ++中的new操作运算符!
- c++-new与delete运算符
- 【C++】new和delete运算符
- C/C++之位运算符与逻辑运算符详解
- c语言之位运算详解
- C语言运算符详解
- 【C/C++】自增运算符++详解
- new 运算符
- new delete运算符
- C# New运算符
- C++ new运算符
- 定位new运算符
- C++学习之map类型
- 黑马程序员——c语言要点总结
- 跨域消息通信
- 获取Android手机中所有的短信
- 快速排序平均情况下时间复杂度计算过程:
- C++ new运算符误用之详解
- 反编译Android APK 源代码和资源文件防止反编译详解
- HDU1334_Perfect Cubes【水题】
- 图的割点(邻接矩阵实现)
- WCF实战Dome(二)--使用IIS发布WCF服务
- TortoiseGit安装和使用的图文教程
- 数据库配置归档
- HDU 5105 Math Problem
- 十大Material Design开源项目