C++和C,在分配动态内存时,分别用new和malloc,但检查其结果的方式完全不同。
在C中,一般是检查返回指针是否为NULL,但这在C++中可能行不通。
#include <iostream>
using namespace std;
const uint64_t MAX_SIZE = 100000000000;
struct GPU {
string m_name;
uint64_t m_serialNumber;
};
int main()
{
struct GPU* pGpu = nullptr;
try {
pGpu = new GPU[MAX_SIZE];
} catch (const std::bad_alloc& e) {
cout << e.what() << endl;
}
if (pGpu == nullptr) {
cout << "pGpu1 new fail!" << endl;
}
// crash
struct GPU* pGpu2 = new GPU[MAX_SIZE];
if (pGpu2 == nullptr) { // 这行不会执行到
cout << "pGpu2 new fail!" << endl;
}
return 0;
}
运行结果
std::bad_alloc
pGpu1 new fail!
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
从运行结果看,当new分配失败时,直接抛出了异常,并不会执行到if (pGpu2 == nullptr) 语句。
假如你的代码中这样的写法,需要注意。