#ifndef STASH_H
#define STASH_H
#include <cassert>
namespace ThinkingInCppDemoLib
{
class PStash
{
private:
int quantity;
int next;
void ** storage;
void inflate(int increase);
public:
PStash() : next(0), storage(0){}
int add(void* element);
void* operator[](int index) const; // 下标操作符,
void* remove(int index); // 就是删除,
int count()
{
return next;
}
~PStash();
};
}
#endif
#include "stash.h"
#include <cstdlib>
#include <cstring>
namespace ThinkingInCppDemoLib
{
int PStash::add(void* element)
{
const int inflateSize = 10;
if (next >= quantity)
inflate(inflateSize);
storage[next++] = element;
return (next - 1);
}
PStash::~PStash()
{
/*for (int i = 0; i < next; i++)
delete void*;*/
delete[] storage;
}
void* PStash::remove(int index)
{
void* v = operator[](index);
if (v != 0) storage[index] = 0;
return v;
}
void* PStash::operator[](int index) const
{
if (index >= next)
return 0;
return storage[index];
}
void PStash::inflate(int increase)
{
assert(increase >= 0);
const int psz = sizeof(void*);
void** st = new void*[quantity + increase];
memset(st, 0, (quantity + increase)*psz); // 这个就是删除,
memcpy(st, storage, quantity*psz);
quantity += increase;
delete[] storage;
storage = st;
}
}
#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 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("main.cpp");
assert(in);
ThinkingInCppDemoLib::PStash 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);
}