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




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