模板化的指針Stash

#ifndef STASH_H  
#define STASH_H  

#include <cassert>  

namespace ThinkingInCppDemoLib
{
	template<class T,int incr = 10>
	class PStash
	{
	private:
		int quantity;
		int next;
		T** storage;
		void inflate(int increase = incr);
	public:
		PStash() : next(0), storage(0){}
		int add(T* element);

		T* operator[](int index) const; // 下標操作符,  
		T* remove(int index);  // 就是刪除,  

		int count()
		{
			return next;
		}
		~PStash();
	};

	template<class T, int incr>
	int PStash<T,incr>::add(T* element)
	{
		if (next >= quantity)
			inflate(incr);

		storage[next++] = element;

		return (next - 1);
	}
	template<class T, int incr>
	PStash<T,incr>::~PStash()
	{
		for (int i = 0; i < next; i++)
		{
			delete storage[i];
			storage[i] = 0;
		}
		delete[] storage;
	}
	template<class T, int incr>
	T* PStash<T,incr>::remove(int index)
	{
		T* v = operator[](index);
		if (v != 0) storage[index] = 0;
		return v;
	}
	template<class T, int incr>
	T* PStash<T,incr>::operator[](int index) const
	{
		//require(index >= 0, "PStash::operator[] index negative");
		if (index >= next)
			return 0;
		return storage[index];
	}
	template<class T, int incr>
	void PStash<T,incr>::inflate(int increase)
	{
		assert(increase >= 0);
		const int psz = sizeof(T*);
		T** st = new T*[quantity + increase];
		memset(st, 0, (quantity + increase)*psz); // 這個就是刪除,  
		memcpy(st, storage, quantity*psz);
		quantity += increase;

		delete[] storage;
		storage = st;
	}
}

#endif 

#include <iostream>  
#include "stash.h"  
#include <string>  
#include <fstream>  


using namespace std;
void testPStash();

int main(int argc, char* argv[])
{
	testPStash();

	return 0;
}

void testPStash()
{
	ThinkingInCppDemoLib::PStash<int> intStash;

	for (int i = 0; i < 25; i++)
		intStash.add(new int(i));  // 這裏就是創建的對象在堆裏,  

	for (int i = 0; i < intStash.count(); i++)
		cout << *(int*)intStash[i] << endl;

	for (int k = 0; k < intStash.count(); k++)
		delete (int*)intStash.remove(k);

	ifstream in;
	in.open("naintest.cpp");
	assert(in);
	ThinkingInCppDemoLib::PStash<string,20> stringStash;

	string line;
	while (getline(in, line))
		stringStash.add(new string(line));

	for (int u = 0; stringStash[u]; u++)
		cout << *(string*)stringStash[u] << endl;

	for (int v = 0; v < stringStash.count(); v++)
		delete (string*)stringStash.remove(v);
}

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