new运算符重载
首先,new和sizeof都是运算符,而strlen是函数。
new和delete是运算符,重载new和delete是可能的。这样做的原因是,有时希望使用某种特殊的动态内存分配方法。例如,可能有些分配子程序,他们的堆已耗尽,自动开始把一个磁盘文件当虚存储使用,或者用户希望控制某一片存储空间的分配等。
重载new和delete的格式如下:
1 void *operator new (size_t size) 2 { 3 .......//完成分配工作 4 return pointer_to_memory; 5 } 6 7 void operator delete(void *p) 8 { 9 ......//释放由p指向的存储空间 10 }
至于为什么一定是这个样子,暂且不知道,这里也不做深究。
1.局部重载new和delete(可以使用成员函数和友元函数两种方式重载)
使用new分配某个重载了new的累的对象空间时,先调用new的重载函数,再调用该类的构造函数,如果该类的构造函数有参数要求,则必须给出对应的实参。
使用了delete释放某个重载了delete的累的对象空间时,先调用类的析构函数,然后再调用重载的delete函数。
1 #include <iostream> 2 using namespace std; 3 #include <stdlib.h> 4 5 class A 6 { 7 private: 8 int x, y, z; 9 public: 10 A(int _x, int _y,int _z) :x(_x), y(_y), z(_z) 11 { 12 cout << "Constructor" << endl; 13 } 14 ~A() 15 { 16 cout << "Destructor" << endl; 17 } 18 void * operator new(size_t size); 19 void operator delete(void *p); 20 friend ostream& operator <<(ostream& os, A& obj); 21 friend void getz(); 22 23 }; 24 25 // 26 void* A::operator new(size_t size) 27 { 28 cout << "my new" << endl; 29 return malloc(size); 30 } 31 32 void A::operator delete(void *p) 33 { 34 cout << "my delete" << endl; 35 free(p); 36 } 37 ostream& operator <<(ostream& os, A& obj) 38 { 39 os << obj.x << ","; 40 os << obj.y << ","; 41 os << obj.z << "\n"; 42 return os; 43 } 44 45 int main() 46 { 47 A *p = new A(1, 2, 3); 48 if (p == NULL) 49 { 50 printf("my new is falure\n"); 51 return -1; 52 } 53 54 cout << *p; 55 56 delete(p); 57 p = NULL; 58 59 int *p1 = new int(3); 60 cout << *p1; 61 delete(p1); 62 p1 = NULL; 63 64 getchar(); 65 }
输出如下:
2.全局重载new和delete
可以在任何类说明之外重在new和delete,使它们成为全局的。当new和delete被重载为全局时,C++原来的new与delete被忽略,并且重载的运算符用于所有类型(包括标准型和用户定义类型)的分配要求。
1 #include <iostream> 2 using namespace std; 3 #include <stdlib.h> 4 5 class A 6 { 7 private: 8 int x, y, z; 9 public: 10 A(int _x, int _y,int _z) :x(_x), y(_y), z(_z) 11 { 12 cout << "Constructor" << endl; 13 } 14 ~A() 15 { 16 cout << "Destructor" << endl; 17 } 18 //void * operator new(size_t size); 19 //void operator delete(void *p); 20 friend ostream& operator <<(ostream& os, A& obj); 21 22 }; 23 24 // 25 void* operator new(size_t size) 26 { 27 cout << "my new" << endl; 28 return malloc(size); 29 } 30 31 void operator delete(void *p) 32 { 33 cout << "my delete" << endl; 34 free(p); 35 } 36 ostream& operator <<(ostream& os, A& obj) 37 { 38 os << obj.x << ","; 39 os << obj.y << ","; 40 os << obj.z << "\n"; 41 return os; 42 } 43 44 int main() 45 { 46 A *p = new A(1, 2, 3); 47 if (p == NULL) 48 { 49 printf("my new is falure\n"); 50 return -1; 51 } 52 53 cout << *p; 54 55 delete(p); 56 p = NULL; 57 58 int *p1 = new int(3); 59 cout << *p1; 60 delete(p1); 61 p1 = NULL; 62 63 getchar(); 64 }
输出: