#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);
}
If I had deleted the wide char array at the end of the function, I couldn’t have processed my queue which references to it. Now, my simple program compiles and works fine, but obviously keeping a garbage in heap isn’t considered as a safe programming practice.
How to delete the “buffer” just after using it last time?
You can use a
queue<unique_ptr<TCHAR[]>>to avoid memory deallocation entirely, or you can simply deallocate the memory before you remove it from thequeuelike so: