C++常识与通识
将引用作为返回值的通常原因是避免创建副本以提高效率,包括其他的函数传参亦是如此
std::nothrow
可以消除抛出异常1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul]; // throwing overload
}
} catch (const std::bad_alloc& e) {
std::cout << e.what() << '\n';
}
while (true) {
int* p = new(std::nothrow) int[100000000ul]; // non-throwing overload
if (p == nullptr) {
std::cout << "Allocation returned nullptr\n";
break;
}
}
}
输出:
1
2std::bad_alloc
Allocation returned nullptr