在google cpp style guide里面明确指出:we don't use exceptions

C++11的noexcept关键字为这种选择提供了便利。

C++11以前,提及malloc和new的区别,总是会强调由malloc返回的指针需要检查是不是null,因为空间分配可能

失败,而由new返回的指针不用检查,因为如若分配失败,它会抛出异常,现在又提供了std::nothrow,使得我们

可以人让new不抛异常,而是返回nullptr表示分配失败,这在需要禁用异常的场合显得很实用,具体的例子如下:

// operator new example
#include <iostream> // std::cout
#include <new> // ::operator new struct MyClass {
int data[];
MyClass() {std::cout << "constructed [" << this << "]\n";}
}; int main () { std::cout << "1: ";
MyClass * p1 = new MyClass;
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object at the newly allocated space std::cout << "2: ";
MyClass * p2 = new (std::nothrow) MyClass;
// allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
// and then constructs an object at the newly allocated space std::cout << "3: ";
new (p2) MyClass;
// does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
// but constructs an object at p2 // Notice though that calling this function directly does not construct an object:
std::cout << "4: ";
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
// allocates memory by calling: operator new (sizeof(MyClass))
// but does not call MyClass's constructor delete p1;
delete p2;
delete p3; return ;
}

可见,只要把原来我们习惯的new T,改成 new (std::nothrow) T,就能使得我们的new expression不抛异常

最新文章

  1. Oracle中已有数据的字段类型修改
  2. mac平台多个php版本快速切换
  3. IOS开发中如何实现自动检测更新APP
  4. Django 查询很经典的
  5. 查看perl及其模块
  6. XTUOJ1250 Super Fast Fourier Transform 暴力
  7. 系统级性能分析工具 — Perf
  8. poj 2100 Graveyard Design
  9. iOS在xib或storyboard里为控件添加圆角、外框和外框颜色
  10. c语言用封装来优化程序
  11. wxPython学习笔记(一)
  12. Android 简单的代码混淆
  13. 【LaTeX排版】LaTeX论文排版&amp;lt;三&amp;gt;
  14. JavaScript正则表达式的坑很深
  15. Android外部存储
  16. POJ 3162 bit区间查询最值+树形DP
  17. MySQL权限和用户安全
  18. bootstrap入门基础
  19. multi-head attention
  20. linux_远程copy

热门文章

  1. python 练习 18
  2. 在VBA中调用工作表函数
  3. javaWeb学习之运用myeclipse结合tomcat开发一些简单的jsp和service
  4. 张艾迪(创始人):DCM的不识人.我说我会像乔布斯一样成为投资者的骄傲
  5. maven install 时提示“程序包 javax.crypto不存在”
  6. SpringMVC整合Quartz实现定时任务以及Tomcat服务执行初始化定时任务
  7. android:configChanges属性
  8. UserAgent:通过浏览器获取用户浏览器等信息
  9. Mysql 字符串处理函数
  10. Sui 弹框固定