I have some generic code for deleting pointers within a vector or a value of a Map.
Is there a better way of doing this (without using shared_ptrs or any o fthe tr1 extensions )?
Also is the code correct?
Here is my code:
I have a namespace
#ifndef CONTAINERDELETE_H #define CONTAINERDELETE_H #include <functional> #include <map> #include <vector> #include <algorithm> namspace ContainerDelete{ template<class A, class B> struct DeleteMap { bool operator()( pair<A,B> &x) const { delete x.second; return true; } }; template<class T> struct DeleteVector { bool operator()(T &x) const { delete x; return true; } }; } #endif I would then use this namespace in some bit of code to delete a map or vector.
Test Map deletion.
#include "ContainerDelete.h" using namespace std; // Test function. void TestMapDeletion() { // Add 10 string to map. map<int,B*> testMap; for( int Idx = 0; Idx < 10; ++Idx ) { testMap[Idx] = new B(); } // Now delete the map in a single line. for_each( testMap.begin(), testMap.end(), ContainerDelete::DeleteMap<int,B*>()); } Test Vector Deletion
// Test Function. void TestVectorDeletion() { // Add 10 string to vector. vector<B*> testVector; for( int Index = 0; Index < 10; ++Index ) { testVector.push_back( new B()); } // Now delete the vector in a single line. for_each( testVector.begin(), testVector.end(), ContainerDelete::DeleteVector<B*>()); } Thanks,
Mike
std::unique_ptr<T>and only look for alternatives if that doesn't fit your needs. Containers of raw pointers are always a bad idea because you don't know who owns the pointed-to objects. You might even have a mix of pointers to dynamic, static and automatic variables. How would the container be able to restrict the amount of damage you can do?