12.26
#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main()
{
/**********1.定義allocator<T>的一個allocator對象,要有類型T********/
allocator<string> alloc;
int n = 100;
/**********2.allocate(n)分配n個爲初始化的內存**********/
auto start = alloc.allocate(n);//分配100個未初始化string的內存
auto p = start;//將分配的內存首地址給p
string s;
/**********3.construct(...,...)初始化內存單元*****************/
while (cin >> s &&p != start + 100)
{
alloc.construct(p++, s);//初始化位置爲p的內存單元
}
const size_t size = p - start;//記錄已經初始化了多少個元素
for (size_t i = 0; i < size; i++)
{
cout << start[i] << endl; //打印已初始化的string,此時應該用start[i],而不用p[i]
}
/************4.destroy已初始化的內存單元************************/
while (--p != start)
{
alloc.destroy(p);//destroy位置爲p的元素
}
/************5.deallocate收回已分配的n個內存單元*********************/
alloc.deallocate(start, n);//收回這n個內存單元
system("pause");
return 0;
}