C++学习之new返回值的误用-new(nothrow)
来源:互联网 发布:json数据生成工具 编辑:程序博客网 时间:2024/04/30 21:21
转自:http://blog.csdn.net/starryheavens/article/details/7002404
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判断分配是否成功是徒劳的。
2.nothrow new/delete不抛出异常的运算符new的形式,new失败时返回NULL。
定义如下:
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的标志性哑元
测试程序:
#include "stdafx.h"
#include <iostream>
#include <new>
using namespace std;
char *GetMemory(unsigned long size)
{
char *p=new(nothrow) char[size];//分配失败,是返回NULL
if(NULL==p)
cout<<"alloc failure!"<<endl;
return p;
}
int main()
{
try
{
char *p=GetMemory(10e11);
//...........
if(p==NULL)
cout<<"failure"<<endl;
delete [] p;
}
catch(const std::bad_alloc &ex)
{
cout<<ex.what()<<endl;
}
return 0;
}
- C++学习之new返回值的误用-new(nothrow)
- new(nothrow)
- nothrow new
- new(nothrow)
- new (nothrow) T() 的原理
- c++的new(std::nothrow)
- new (nothrow) T() 的原理
- new(std::nothrow) 和 new() 的区别
- new && new(std::nothrow)
- new && new(std::nothrow)
- C/C++ 误区之五:检查 new 的返回值
- new (std::nothrow) 与 new
- new (std::nothrow) 与 new
- new(std::nothrow) 和 new
- new 和 new(std::nothrow)
- 关于 new(std::nothrow)
- new(std::nothrow)
- new的三种使用方式:plain new、nothrow new、placement new.
- Oracle中的ROWNUM
- seam 中url支持中文的方法
- 12 个最好的免费网站速度和性能测试工具
- Java通过JNI调用C++程序
- 通过shell脚本批量部署ssh私钥认证以及批量操作工具pssh的简单使用
- C++学习之new返回值的误用-new(nothrow)
- 12款很棒的浏览器兼容性测试工具推荐
- rails4 onclick事件不响应
- struts2整理(result)-002
- 理解WebKit和Chromium: Android 4.4 上的Chromium WebView
- EL标签if判断的使用
- 【iOS】CoreGraphics简单绘图
- 在培训机构待了一年了,都不知道学的知识用不用的到!!
- android 意见反馈