基于C++函数模板实现堆栈切换的一种方法

//描述: 堆内存申请
//参数:@stack 栈内存
//		@heap 堆内存
//返回:成功返回true,反之为false
template <typename T, WORD wMaxNum>
bool MgrMemNew(bool &fUseHeap, WORD wCurNum, T (&stack)[wMaxNum], T **heap)
{
	if (wCurNum > wMaxNum)
	{
		*heap = new T[wCurNum];
		if (*heap == nullptr)
		{
			printf("MgrMemNew(): new failed! Type=%s\n", typeid(stack).name());
			return false;
		}
		memset((BYTE*)*heap, 0, sizeof(T)*wCurNum);
		fUseHeap = true;
	}
	else
	{
		*heap = stack;
		memset((BYTE*)*heap, 0, sizeof(T)*wMaxNum);
		fUseHeap = false;
	}

	return true;
}

//描述:堆内存释放
//参数:@fUsageHeap 栈内存标识
//		@heap 需释放的栈内存
//返回:无
template <typename T>
void MgrMemDel(bool &fUseHeap, T *heap)
{
	if (fUseHeap)
	{
		delete[] heap;
		heap = nullptr;
		fUseHeap = false;
	}
		
}
typedef struct {
	WORD wNum;
	int iArray[8];
	bool fHeap;
	int *piArray;
}TStackHeap;



TStackHeap stackHeap = { 0 };

stackHeap.wNum = 7;
MgrMemNew(stackHeap.fHeap, stackHeap.wNum, stackHeap.iArray, &stackHeap.piArray);
MgrMemDel(stackHeap.fHeap, stackHeap.piArray);

 

 

上一篇:最短路径算法


下一篇:heapq-堆队列算法