> 文章列表 > new动态内库管理库学习

new动态内库管理库学习

new动态内库管理库学习

new文件是动态内存管理库的一部分,特别提供低层内存管理特性。 它包括bad_alloc, bad_array_new_length,nothrow_t,align_val_t类nothrow常量,以及函数 operator newoperator new[],operator deleteoperator delete[],get_new_handler,set_new_handle等,
下面介绍它们的基本使用。

1.new与delete

new是动态分析内存,delete是释放分配的内存,它们是成对使用的。

代码示例

#include <iostream>
#include <new>using namespace std;class Person {
public:Person(string name, int age) :m_name(name),m_age(age) { }private:string m_name;int m_age;
};int main()
{Person *p = new Person("camel", 28);cout << "p==============" << p << endl;cout << "sizeof(*p)=====" << sizeof(*p) << endl;//debug 版32个字节 release版28个字节delete p;cout << "Hello World!" << endl;return 0;
}

运行结果:

 2.new[]和delete[]

new[]为数组分配内存但没有初始化,释放时使用delete[],它们是成对使用。

示例代码:

int main()
{int *p2 = new int[2];cout << "p2=============" << p2 << endl;cout << "sizeof(*p2)====" << sizeof(*p2) << endl;cout << "p2[0]==========" << p2[0] << endl;cout << "p2[1]==========" << p2[1] << endl;p2[0] = 20;p2[1] = 30;cout << "p2[0]==========" << p2[0] << endl;cout << "p2[1]==========" << p2[1] << endl;delete[] p2;cout << "Hello World!" << endl;return 0;
}

 运行结果:

3.bad_alloc

 bad_alloc 是分配函数作为异常抛出的对象类型,以报告存储分配失败。

int main()
{try {while (true) {new int[100000000ul];   // 抛出重载}} catch (const std::bad_alloc& e) {cout << "exception info:" << e.what() << endl;}cout << "Hello World!" << endl;return 0;
}

运行结果:

 4.nothrow

nothrow是std::nothrow_t类型的常量,当内存分析失败时不抛出异常,这个时候返回为nullptr。

示例代码:

int main()
{while (true) {int* p = new(std::nothrow) int[100000000ul]; // 不抛出重载if (p == nullptr) {cout << "Allocation returned ========================= nullptr" << endl;break;}}cout << "Hello World!" << endl;return 0;
}

运行结果:

 5.bad_array_new_length

bad_array_new_length是new表达式出现异常时报告非法数组长度的对象类型。有下在三种情况会抛出异常:

1) 数组长度为负

2) 新数组的总大小将超过实现定义最大值

3) 初始化器子句的数量超出要初始化的元素数量

仅数组第一维可生成此异常;第一维外的维数是常量表达式,在编译时得到检查。

示例代码:

int main()
{int negative = -1;int small = 1;int large = INT_MAX;try {new int[negative];           // 负大小: bad_array_new_lengthnew int[small]{1,2,3};       // 过多初始化器: bad_array_new_lengthnew int[large][1000000];     // 过大: bad_alloc 或 bad_array_new_length} catch(const std::bad_array_new_length &e) {cout << "exception info:" << e.what() << '\\n';} catch(const std::bad_alloc &e) {cout << "exception info:" << e.what() << '\\n';}cout << "Hello World!" << endl;return 0;
}

运行结果:

 

参考:

标准库头文件 <new> - cppreference.com

电影影评