c++ primer 12.2.2节练习(使用allocate五步走)

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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章