指针的Stash 将void** 删除指针

本文档介绍了一个名为PStash的C++类,用于存储和管理void**类型的指针。PStash类提供了添加、删除、下标操作以及动态扩容等功能,支持存储和检索不同类型的对象。通过测试函数testPStash,展示了如何使用PStash存储和删除int及std::string对象,并确保正确释放内存。
#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);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值