天天看点

C++ Primer 第五版 中文版 练习 12.26 个人code

C++ Primer 第五版 中文版 练习 12.26

题目:用 allocator 重写第 427 页中的程序。

答:对于这个 allocator 由于我智商略低,或者其它原因,实在看不出来这个allocator的用法,或者有其它什么优势。所以用不好,以下代码

不完善,没有释放分配的内存,因为我发现只要试图去 deallocator 分配的内存就分出错,不知道问题出在什么地方。

#include <iostream>
#include <memory>
#include <string>
#include <vector>

using namespace std;

int main()
{
	allocator<string> stralloc;
	string s;
	auto p = stralloc.allocate(20);
	auto q = p;
	while (cin >> s&&q!=p+20)
	{
		stralloc.construct(q++, s);
	}

	while (q != p)
	{
		cout << *p<< " ";
		stralloc.destroy(p);
		++p;	
	}

	cout << endl;
	
//	stralloc.deallocate(p, 20);  按书的说的理解,分配的内存在不用的时候可以归还给系统,但我只要加上这句程序就出错了……
	return 0;
}
           

继续阅读