C++11 不抛异常的new operator

在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不抛异常

上一篇:bzoj 1217: [HNOI2003]消防局的设立


下一篇:cloudstack 创建虚拟机失败