-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathnew_delete.cpp
More file actions
54 lines (47 loc) · 1.28 KB
/
new_delete.cpp
File metadata and controls
54 lines (47 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;
// 先调用operator new 开辟内存空间、然后调用对象的构造函数(初始化)
void* operator new(size_t size)
{
void *p = malloc(size);
if (p == nullptr)
throw bad_alloc();
cout << "operator new addr:" << p << endl;
return p;
}
// delete p; 调用 p 指向对象的析构函数、再调用 operator delete 释放内存空间
void operator delete(void *ptr) _NOEXCEPT
{
cout << "operator delete addr:" << ptr << endl;
free(ptr);
}
void* operator new[](size_t size)
{
void *p = malloc(size);
if (p == nullptr)
throw bad_alloc();
cout << "operator new[] addr:" << p << endl;
return p;
}
void operator delete[](void *ptr) _NOEXCEPT
{
cout << "operator delete[] addr:" << ptr << endl;
free(ptr);
}
int main()
{
try
{
int *p = new int;
delete p;
}
catch(const bad_alloc& e)
{
std::cerr << e.what() << '\n';
}
// new[] / delete[] 最好是配套使用,这里使用基础类型没问题
// 如果涉及到类就不行了,因为 new [] 时往往会多分配 4 个字节存放多少个对象,以便在 delete [] 时候知道调用多少个对象的析构函数
int *arr = new int[3];
delete []arr;
return 0;
}