重载 class A的new/delete 以及 new[]/delete[]运算符:
成功返回非空指针,失败返回空指针
#include <iostream>
#include <cstdlib>
using namespace std;
class A {
public:
A (int var = 0) : m_var (var) {
cout << "A构造:" << this << endl;
}
~A (void) {
cout << "A析构:" << this << endl;
}
static void* operator new (size_t size) {
void* pv = malloc (size);
cout << "new:" << size << ' ' << pv
<< endl;
return pv;
}
static void operator delete (void* pv) {
cout << "delete:" << pv << endl;
free (pv);
}
static void* operator new[] (size_t size){
void* pv = malloc (size);
cout << "new[]:" << size << ' ' << pv
<< endl;
return pv;
}
static void operator delete[] (void* pv) {
cout << "delete[]:" << pv << endl;
free (pv);
}
private:
int m_var;
string m_str;
};
int main (void) {
A* pa = new A (100);
// A* pa = (A*)A::operator new (sizeof (A));
// A::A (pa, 100);
cout << "pa = " << pa << endl;
delete pa;
// A::~A (pa);
// A::operator delete (pa);
pa = new A[5] {200, 300, 400, 500, 600};
cout << "pa = " << pa << endl;
cout << *((int*)pa-1) << endl;
delete[] pa;
// delete pa;
// cout << 2 > 1 << endl;
cout << (2 > 1) << endl;
return 0;
}
来源:CSDN
作者:Johhny Rade
链接:https://blog.csdn.net/uncle103/article/details/103813323