new”是C++的一个关键字,同时也是操作符。关于new的话题非常多,因为它确实比较复杂,也非常神秘,下面我将把我了解到的与new有关的内容做一个总结。
1 class A 2 { 3 int i; 4 public: 5 A(int _i) :i(_i*_i) {} 6 void Say() { printf("i=%d/n", i); } 7 }; 8 //调用new: 9 A* pa = new A(3);
那么上述动态创建一个对象的过程大致相当于以下三句话(只是大致上):
1 A* pa = (A*)malloc(sizeof(A)); 2 pa->A::A(3); 3 return pa;
1 class A 2 { 3 public: 4 void* operator new(size_t size) 5 { 6 printf("operator new called/n"); 7 return ::operator new(size); 8 } 9 }; 10 11 A* a = new A();
这里通过::operator new调用了原有的全局的new,实现了在分配内存之前输出一句话。全局的operator new也是可以重载的,但这样一来就不能再递归的使用new来分配内存,而只能使用malloc了:
1 void* operator new(size_t size) 2 { 3 printf("global new/n"); 4 return malloc(size); 5 }
1 #include <new.h> 2 3 void main() 4 { 5 char s[sizeof(A)]; 6 A* p = (A*)s; 7 new(p) A(3); //p->A::A(3); 8 p->Say(); 9 }
对头文件<new>或<new.h>的引用是必须的,这样才可以使用placement new。这里“new(p) A(3)”这种奇怪的写法便是placement new了,它实现了在指定内存地址上用指定类型的构造函数来构造一个对象的功能,后面A(3)就是对构造函数的显式调用。这里不难发现,这块指定的地址既可以是栈,又可以是堆,placement对此不加区分。但是,除非特别必要,不要直接使用placement new ,这毕竟不是用来构造对象的正式写法,只不过是new operator的一个步骤而已。使用new operator地编译器会自动生成对placement new的调用的代码,因此也会相应的生成使用delete时调用析构函数的代码。如果是像上面那样在栈上使用了placement new,则必须手工调用析构函数,这也是显式调用析构函数的唯一情况:
1 p->~A();
1 void* operator new(size_t size) 2 { 3 void* p = null 4 while(!(p = malloc(size))) 5 { 6 if(null == new_handler) 7 throw bad_alloc(); 8 try 9 { 10 new_handler(); 11 } 12 catch(bad_alloc e) 13 { 14 throw e; 15 } 16 catch(…) 17 {} 18 } 19 return p; 20 }
在默认情况下,new_handler的行为是抛出一个bad_alloc异常,因此上述循环只会执行一次。但如果我们不希望使用默认行为,可以自定义一个new_handler,并使用std::set_new_handler函数使其生效。在自定义的new_handler中,我们可以抛出异常,可以结束程序,也可以运行一些代码使得有可能有内存被空闲出来,从而下一次分配时也许会成功,也可以通过set_new_handler来安装另一个可能更有效的new_handler。例如:
1 void MyNewHandler() 2 { 3 printf(“New handler called!/n”); 4 throw std::bad_alloc(); 5 } 6 7 std::set_new_handler(MyNewHandler);
1 class SomeClass 2 { 3 static int count; 4 SomeClass() {} 5 public: 6 static SomeClass* GetNewInstance() 7 { 8 count++; 9 return new SomeClass(); 10 } 11 };
静态变量count用于记录此类型生成的实例的个数,在上述代码中,如果因new分配内存失败而抛出异常,那么其实例个数并没有增加,但count变量的值却已经多了一个,从而数据结构被破坏。正确的写法是:
1 static SomeClass* GetNewInstance() 2 { 3 SomeClass* p = new SomeClass(); 4 count++; 5 return p; 6 }
这样一来,如果new失败则直接抛出异常,count的值不会增加。类似的,在处理线程同步时,也要注意类似的问题:
1 void SomeFunc() 2 { 3 lock(someMutex); //加一个锁 4 delete p; 5 p = new SomeClass(); 6 unlock(someMutex); 7 }
1 template <class T1, class T2> 2 inline void construct(T1* p, const T2& value) 3 { 4 new(p) T1(value); 5 }
此函数接收一个已构造的对象,通过拷贝构造的方式在给定的内存地址p上构造一个新对象,代码中后半截T1(value)便是placement new语法中调用构造函数的写法,如果传入的对象value正是所要求的类型T1,那么这里就相当于调用拷贝构造函数。类似的,因使用了placement new,编译器不会自动产生调用析构函数的代码,需要手工的实现:
1 template <class T> 2 inline void destory(T* pointer) 3 { 4 pointer->~T(); 5 }
与此同时,STL中还有一个接收两个迭代器的destory版本,可将某容器上指定范围内的对象全部销毁。典型的实现方式就是通过一个循环来对此范围内的对象逐一调用析构函数。如果所传入的对象是非简单类型,这样做是必要的,但如果传入的是简单类型,或者根本没有必要调用析构函数的自定义类型(例如只包含数个int成员的结构体),那么再逐一调用析构函数是没有必要的,也浪费了时间。为此,STL使用了一种称为“type traits”的技巧,在编译器就判断出所传入的类型是否需要调用析构函数:
1 template <class ForwardIterator> 2 inline void destory(ForwardIterator first, ForwardIterator last) 3 { 4 __destory(first, last, value_type(first)); 5 }
其中value_type()用于取出迭代器所指向的对象的类型信息,于是:
1 template<class ForwardIterator, class T> 2 inline void __destory(ForwardIterator first, ForwardIterator last, T*) 3 { 4 typedef typename __type_traits<T>::has_trivial_destructor trivial_destructor; 5 __destory_aux(first, last, trivial_destructor()); 6 } 7 //如果需要调用析构函数: 8 template<class ForwardIterator> 9 inline void __destory_aux(ForwardIterator first, ForwardIterator last, __false_type) 10 { 11 for(; first < last; ++first) 12 destory(&*first); //因first是迭代器,*first取出其真正内容,然后再用&取地址 13 } 14 //如果不需要,就什么也不做: 15 tempalte<class ForwardIterator> 16 inline void __destory_aux(ForwardIterator first, ForwardIterator last, __true_type) 17 {}
因上述函数全都是inline的,所以多层的函数调用并不会对性能造成影响,最终编译的结果根据具体的类型就只是一个for循环或者什么都没有。这里的关键在于__type_traits<T>这个模板类上,它根据不同的T类型定义出不同的has_trivial_destructor的结果,如果T是简单类型,就定义为__true_type类型,否则就定义为__false_type类型。其中__true_type、__false_type只不过是两个没有任何内容的类,对程序的执行结果没有什么意义,但在编译器看来它对模板如何特化就具有非常重要的指导意义了,正如上面代码所示的那样。__type_traits<T>也是特化了的一系列模板类:
1 struct __true_type {}; 2 struct __false_type {}; 3 template <class T> 4 struct __type_traits 5 { 6 public: 7 typedef __false _type has_trivial_destructor; 8 …… 9 }; 10 template<> //模板特化 11 struct __type_traits<int> //int的特化版本 12 { 13 public: 14 typedef __true_type has_trivial_destructor; 15 …… 16 }; 17 …… //其他简单类型的特化版本
如果要把一个自定义的类型MyClass也定义为不调用析构函数,只需要相应的定义__type_traits<T>的一个特化版本即可:
1 template<> 2 struct __type_traits<MyClass> 3 { 4 public: 5 typedef __true_type has_trivial_destructor; 6 …… 7 };
1 char* s = new char[100]; 2 …… 3 delete s;
严格的说,上述代码是不正确的,因为我们在分配内存时使用的是new[],而并不是简单的new,但释放内存时却用的是delete。正确的写法是使用delete[]:
1 delete[] s;
但是,上述错误的代码似乎也能编译执行,并不会带来什么错误。事实上,new与new[]、delete与delete[]是有区别的,特别是当用来操作复杂类型时。假如针对一个我们自定义的类MyClass使用new[]:
1 MyClass* p = new MyClass[10];
1 delete[] p;
1 class MyClass 2 { 3 int a; 4 public: 5 MyClass() { printf("ctor/n"); } 6 ~MyClass() { printf("dtor/n"); } 7 }; 8 9 void* operator new[](size_t size) 10 { 11 void* p = operator new(size); 12 printf("calling new[] with size=%d address=%p/n", size, p); 13 return p; 14 } 15 16 // 主函数 17 MyClass* mc = new MyClass[3]; 18 printf("address of mc=%p/n", mc); 19 delete[] mc;
运行此段代码,得到的结果为:(VC2005)
1 template <class T> 2 T* New[](int count) 3 { 4 int size = sizeof(T) * count + 4; 5 void* p = T::operator new[](size); 6 *(int*)p = count; 7 T* pt = (T*)((int)p + 4); 8 for(int i = 0; i < count; i++) 9 new(&pt[i]) T(); 10 return pt; 11 }
上述示意性的代码省略了异常处理的部分,只是展示当我们对一个复杂类型使用new[]来动态分配数组时其真正的行为是什么,从中可以看到它分配了比预期多4个字节的内存并用它来保存对象的个数,然后对于后面每一块空间使用placement new来调用无参构造函数,这也就解释了为什么这种情况下类必须有无参构造函数,最后再将首地址返回。类似的,我们很容易写出相应的delete[]的实现代码:
1 template <class T> 2 void Delete[](T* pt) 3 { 4 int count = ((int*)pt)[-1]; 5 for(int i = 0; i < count; i++) 6 pt[i].~T(); 7 void* p = (void*)((int)pt – 4); 8 T::operator delete[](p); 9 }
1 char *p = 0; 2 for(int i = 0; i < 40; i += 4) 3 { 4 char* s = new char[i]; 5 printf("alloc %2d bytes, address=%p distance=%d/n", i, s, s - p); 6 p = s; 7 }

