In an application I am maintainig I came across a persistence class that had 6 functions that all did the same thing except for the type of item that was being persisted. These items are all of the same base class - a candidate for a template function.
However once I had converted them it would seem that when the function is being stepped into to the container that is being written to is always empty (a temporary copy being created?) despite the fact it should have several items in it. To be sure, inspecting the container in the debugger it has zero items it. Also the writing function triggers an event that notifies the client of an change in status, but when that thread goes to extract the item from the deque it is always now empty.
The base class is called CItem and all other items are specialities of that Item (CErrorItem
, etc). They all are persisted in a deque (std::deque<std::tr1::shared_ptr<CItem>> m_items;
), and to disk. The items are written to disk correctly. Once processed correctly the items are removed from both the deque and disk.
Items are added with the code m_persistence.Add<CErrorItem>(errorItem);
All data for items are stored in simple structs (eg ErrorItemInfo
), and the Items take these simple data stores in their constructor. It is this struct that is denoted by the U
in the below code. The T
is the derived CItem
.
The function that adds the items is the following:
template <typename T, typename U>
std::tr1::shared_ptr<T> CPersistenceManager::Add(const U& item)
{
std::tr1::shared_ptr<T> newItem = std::tr1::shared_ptr<T>(new T(item));
// .. a couple of lines calling helper functions to generated a unique timestamped filename
newItem->Write(filename); // this writes to disk and works.
m_items.push_back(newItem); // m_items is always empty
SetEvent(m_itemAddedEvent); // notify the client an item has been added.
return newItem;
}
The simplest solution is to revert the code back to specific functions, and probably I will do that, but I would like to understand why this is occuring so I can avoid it in the future.