首页 > 代码库 > C++ std::allocator<T>使用

C++ std::allocator<T>使用

基础知识通道:http://blog.csdn.net/Xiejingfa/article/details/50955295

 

C/C++:

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 #define allocate_length 100000
 6 
 7 
 8 int main()
 9 {
10 
11     //allocator比new快的原因:分离分配和初始化这两个操作allocator少执行一步,new则一般执行两次(初始化和赋值);
12 
13 
14     std::clock_t start = 0, end = 0;
15 
16     start = clock();
17     std::string *str1 = new std::string[allocate_length];
18     auto str6=str1;
19     for (int i = 0; i < allocate_length; i++)
20     {
21         *str1++ = "Hello World";
22     }
23 
24     delete []str6;
25     end = clock();
26     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
27 
28 
29 
30 
31     start = clock();
32     std::allocator<std::string> str_allocate;
33     std::string *str3 = str_allocate.allocate(allocate_length); //分配20个string原始内存
34     auto str4=str3;
35 
36     //方法一:使用默认构造
37     for (int i = 0; i < allocate_length; i++)
38     {
39         str_allocate.construct(str3++,"Hello World");
40     }
41 
42     //方法二:使用allocator的伴随算法(分别是带n与不带)
43     //其他算法:std::uninitialized_copy(iterator begin,iterator end,T value);
44 
45     //std::uninitialized_fill_n(str3,allocate_length,"Hello World");
46 
47 
48     //str_allocate.destroy()调用对象的析构,但是内存还是由allocator控制,需要自己释放
49     str_allocate.deallocate(str4,allocate_length);
50     end = clock();
51 
52     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
53 
54 
55     return 0;
56 }

 

C++ std::allocator<T>使用