如果定义一个类,有其默认的构造函数,则使用new动态实例化一个对象数组,不是件难事,如下代码:
1 #include <memory>
2 #include <iostream>
3
4 using namespace std;
5
6 class Animal
7 {
8 public:
9 #if 1 //用于后面演示,无默认构造函数
10 Animal() : num(0)
11 {
12 cout << "Animal constructor default" << endl;
13 }
14 #endif
15 Animal(int _num) : num(_num)
16 {
17 cout << "Animal constructor param" << endl;
18 }
19
20 ~Animal()
21 {
22 cout << "Animal destructor" << endl;
23 }
24
25 void show()
26 {
27 cout << this->num << endl;
28 }
29
30 private:
31 int num;
32 };
33
34 int main()
35 {
36 Animal *ani = new Animal[5];
37
38 delete[]ani;
39
40 system("pause");
41 return 0;
42 }
运行结果:
但是,如果没有默认构造函数,会出现怎么样呢?
看下图报错提示:
那要如何实例化一个没有默认构造函数的对象数组呢?
下面我将介绍两种方法:
1. 使用C++11新特性allocator类
2. 使用placement new 即operator new(第三个重载版本)void* operator new(size_t size, void *p)函数
一、allocator类
对于allocator类,请看 我的另一篇blog http://www.cnblogs.com/SimonKly/p/7819122.html
请看一下代码关于使用如何实现无默认构造函数,动态实例化对象数组的allocator方法
1 //#include "CAnimal.h" 2 #include <memory> 3 #include <iostream> 4 5 using namespace std; 6 7 class Animal 8 { 9 public: 10 #if 1 //即使为0,没有默认构造也是可以, 11 Animal() : num(0) 12 { 13 cout << "Animal constructor default" << endl; 14 } 15 #endif 16 Animal(int _num) : num(_num) 17 { 18 cout << "Animal constructor param" << endl; 19 } 20 21 ~Animal() 22 { 23 cout << "Animal destructor" << endl; 24 } 25 26 void show() 27 { 28 cout << this->num << endl; 29 } 30 31 private: 32 int num; 33 }; 34 35 /* 36 由于allocator将内存空间的分配和对象的构建分离 37 故使用allocator分为以下几步: 38 1.allocator与类绑定,因为allocator是一个泛型类 39 2.allocate()申请指定大小空间 40 3.construct()构建对象,其参数为可变参数,所以可以选择匹配的构造函数 41 4.使用,与其它指针使用无异 42 5.destroy()析构对象,此时空间还是可以使用 43 6.deallocate()回收空间 44 */ 45 46 int main() 47 { 48 allocator<Animal> alloc; //1. 49 Animal *a = alloc.allocate(5); //2. 50 51 //3. 52 alloc.construct(a, 1); 53 alloc.construct(a + 1); 54 alloc.construct(a + 2, 3); 55 alloc.construct(a + 3); 56 alloc.construct(a + 4, 5); 57 58 //4. 59 a->show(); 60 (a + 1)->show(); 61 (a + 2)->show(); 62 (a + 3)->show(); 63 (a + 4)->show(); 64 65 //5. 66 for (int i = 0; i < 5; i++) 67 { 68 alloc.destroy(a + i); 69 } 70 //对象销毁之后还可以继续构建,因为构建和内存的分配是分离的 71 //6. 72 alloc.deallocate(a, 5); 73 74 cin.get(); 75 return 0; 76 }