C++ 中,<new> 是一个非常重要的头文件,它包含了用于动态内存分配的函数和异常类型。
动态内存分配允许程序在运行时请求内存,这在处理不确定大小的数据结构时非常有用。
<new> 头文件关键组件:
new 运算符: 动态分配内存,允许程序在运行时请求内存。
delete 运算符: 释放动态分配的内存,释放之前使用new分配的内存。
nothrow 运算符:内存分配失败时不抛出异常。
std::bad_alloc 异常:当内存分配失败时抛出,可以通过try-catch块来捕获并处理这个异常。
动态分配单个对象或数组:
#include <iostream>
#include <new>
class MyClass {
public:
int value;
MyClass() : value(0) {}
};
int main() {
MyClass* myObject = new MyClass; // 分配一个 MyClass 对象
myObject->value = 10;
std::cout << "Value: " << myObject->value << std::endl;
delete myObject; // 释放内存
int* myArray = new int[10]; // 分配一个包含10个整数的数组
for (int i = 0; i < 10; ++i) {
myArray[i] = i * 2;
}
for (int i = 0; i < 10; ++i) {
std::cout << "Array[" << i << "]: " << myArray[i] << std::endl;
}
delete[] myArray; // 释放数组内存
return 0;
}
分配一个大数组失败
#include <iostream>
#include <new>
int main() {
int* myArray = new(std::nothrow) int[10000000]; // 尝试分配一个大数组
if (!myArray) {
std::cout << "Memory allocation failed." << std::endl;
} else {
std::cout << "Memory allocation succeeded." << std::endl;
delete[] myArray; // 释放内存
}
return 0;
}
异常处理
#include <iostream>
#include <new>
int main() {
try {
int* myArray = new int[10000000]; // 尝试分配一个大数组
std::cout << "Memory allocation succeeded." << std::endl;
delete[] myArray; // 释放内存
} catch (const std::bad_alloc& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}