【发布时间】:2012-09-13 11:27:45
【问题描述】:
#ifndef UNICODE
#define UNICODE
#endif
#include <iostream>
#include <Windows.h>
#include <queue>
using namespace std;
void addSomeContent(queue<TCHAR*> &s)
{
static int counter=0;
TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap
wsprintf(buffer,TEXT("foo%d"),counter);
s.push(buffer);
counter++;
if(counter < 10)
addSomeContent(s);
}
int main (void)
{
queue<TCHAR*> strings;
addSomeContent(strings);
while(!strings.empty())
{
wcout<<strings.front()<<endl;
strings.pop();
}
//Here I want to destroy the "buffer" from the function "addSomeContent"
wcout<<TEXT("Memory has been cleaned!\n");
system("pause");
return (0);
}
如果我在函数末尾删除了宽字符数组,我就无法处理引用它的队列。现在,我的简单程序编译并运行良好,但显然在堆中保留垃圾并不被认为是一种安全的编程实践。
上次使用后如何删除“缓冲区”?
【问题讨论】:
-
queue<unique_ptr<TCHAR>>或只是delete[] strings.back()在strings.pop()之前。你也应该使用back而不是front -
@SethCarnegie 从您的评论中做出回答。
-
@SethCarnegie 如果我想实现 FIFO 数据结构,为什么要返回?
-
FWIW,让操作系统处理堆释放并没有什么不安全,只要它是您生命周期设计的一部分。 (这是假设您使用的是这样的操作系统。)事实上,事后尝试添加显式解除分配通常更具破坏性只是为了最佳实践.
-
@0x6B6F77616C74 你说得对,我忘了你用的是
queue,那应该是front。我把它放在一个答案中。
标签: c++ pointers memory-management stl heap-memory