A Safer STL Container Class

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

class CElement
{
unsigned int m_magic_number;

CElement::CElement(const int index)
: m_magic_number(0xfeedface), m_index(index)
{
}

There are probably some other ways of doing it. For example, delete operator uses _BLOCK_TYPE_IS_VALID macro in debug mode. Either way, it is much safer to use for a little speed decrease.
Note: In case your class is derived from some base class, you would have to use 4 bytes offset when dereferencing a pointer inside IsBlockValid function:


return (*((unsigned int*)((int)pBlock + 4)) == 0xfeedface);

I also added some functions to make it MFC like: GetFirst(), GetNext(), RemoveLastRead(), etc.
In the sample code I added 10 elements into the map. Then I deleted elements 5 and 7 outside the map. Then I looped through displaying the content. Notice that after going through all the elements CTidyMap reports 8 to be the actual size.

Example Usage


CTidyMap<CElement, int&gt mymap;
CElement* pElement[10];

for(int i = 0; i < 10; i++) {
pElement[i] = new CElement(i);
mymap.Add(pElement[i], i);
}

cout << “Number of elements in the map: ”
<< mymap.GetCount() << endl;

delete pElement[5];

cout << “Deleted Element number 5” << endl;
delete pElement[7];

cout << “Deleted Element number 7” << endl;

cout << “Still does not know about elements being deleted, size: ”
<< mymap.GetCount() << endl;

CElement* pExElem = mymap.GetFirst();
while(pExElem) {
cout << “Found Element number: ”
<< pExElem->GetIndex()
<< endl;

pExElem = mymap.GetNext();
}

cout << “Now the number of elements in the map: ”
<< mymap.GetCount()
<< endl;

Output


Number of elements in the map: 10
Deleted Element number 5
Deleted Element number 7
Still does not know about elements being deleted, size: 10
Found Element number: 0
Found Element number: 1
Found Element number: 2
Found Element number: 3
Found Element number: 4
Found Element number: 6
Found Element number: 8
Found Element number: 9
Now the number of elements in the map: 8

Bonus

I also made the feedface optional so if you initialize it like this:


CTidyMap<CElement, int&gt mymap = false;

you can watch the program crash.

Downloads

Download demo project – 5 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read