Memory Management on Objects in a C++ Collection - c++

I have a map that relates integers to vectors (of objects). These vectors represent a set of tasks to perform. In order to reduce the amount of copying going on while using this map and vector I've set them up to make use of pointers.
std::map<int, std::vector<MyObject *> *> myMap;
During initialization of the class that holds myMap, I populate myMap by creating a new vector filled with new MyObjects.
What I'm concerned with, however, is memory management. Now I have these various objects sitting out on the heap somewhere and I am responsible for cleaning them up when I'm done with them. I also know that I will NEVER be done with them until the program is finished. But what about in 10 weeks when someone decides that a clever way to modify this app involves removing items from the map/vectors. This would cause a memory leak.
My question is how can I handle the proper deallocation of these objects so that even if they get removed via an STL function that the objects get successfully deallocated?
Your help is much appreciated, let me know if I've missed anything critical!
Thanks!

Use a smart pointer boost:shared_ptr rather than raw pointers, that way when the object is destroyed it will clear up the heap allocated memory as well.
boost::shared_ptr http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm
Also is there really a reason to have pointers to the vectors? They take up almost no space, and objects within an std::map are not moved anyway (unlike the objects in a vector which are moved/copied each time the vector reallocates, eg to get more space).
EDIT:
Also shared_ptr is a component of tr1, and I'm pretty sure is in the next standard, so your compiler may already have it. There are also lots of other smart pointers around that are STL safe to give you an idea of how to write your own, a quick search on Google should find them.
EDIT2:
Just checked and the Visual Studio 2008 implementation of TR1 includes the shared_ptr which is included in the Visual C++ 2008 Feature Pack. I expect many other vendors have implementations available for at least parts of TR1, so if your not using VS search your vendors site for TR1 support.

I agree the use of smart pointers is a good way to go, but there are at least two alternatives:
a) Copying may not be as expensive as you think it is. Try implementing a map of values
std::map<int, std::vector<MyObject>> myMap;
b) Replace the vector with a class of your own that wraps the vector. In that classes destructor, handle the deallocation. You could also provide methods for adding and removing MyObjects.

Using a shared pointer (as suggested by others) is the best solution.
If you really know you will never be done with them, then they don't technically need deallocating. If this really is desired behaviour, just document it so that someone doesn't come along in 10 weeks and mistake this for a genuine leak.

Thank you all for the good answers. I think currently I'm leaning towards a vector of values solution currently. The main reason is that std::auto_ptr doesn't work with collections due to the fact that it is uncopyable. This would be the only implementation of a smart pointer that I would be able to use without going through a burdensome vetting process or rolling my own.
The good news is your responses led me down a very good road. I learned about RAII, dangers about exception handling and how to minimize them, and put enough vigilance into my design that I can be satisfied with its "Correctness".
Attached are some links that I found helpful along the way. I hope that anyone coming to a similar problem will find these links helpful.
RAII Resource
Smart Pointers in C++
Boost Smart Pointers
More background/implementation details about Smart pointers

If the ownership of each pointer is not shared among different entries in the vectors/maps and so you only mean reducing the copying done at insertion time, then you should also consider boost's Pointer Container library.

To elaborate on minimizing copying when using map<,vector<Object>>:
Closely look at the interfaces of map and vector. They mostly return references to the contained items, and if you preserve the reference in passing these things around, no copying will occur.
Bad example:
std::vector<MyObject> find_objects( const std::map<int,std::vector<MyObject>> & map, int i ) {
const std::map<int,std::vector<MyObject>>::const_iterator it = map.find( i );
if ( it != map.end() )
return it->second;
else
return std::vector<MyObject>();
}
// ...
const std::vector<MyObject> objects = find_objects(/*...*/);
Better:
const std::vector<MyObject> & find_objects( const std::map<int,std::vector<MyObject>> & map, int i ) {
const std::map<int,std::vector<MyObject>>::const_iterator it = map.find( i );
if ( it != map.end() )
return it->second;
static const std::vector<MyObject> none();
return none;
}
// ...
const std::vector<MyObject> & objects = find_objects(/*...*/);
-> no copying

Related

C++: pointers and abstract array classes

I am relatively new to pointers and have written this merge function. Is this effective use of pointers? and secondly the *two variable, it should not be deleted when they are merged right? that would be the client´s task, not the implementer?
VectorPQueue *VectorPQueue::merge(VectorPQueue *one, VectorPQueue *two) {
int twoSize = two->size();
if (one->size() != 0) {
for (int i = 0; i < twoSize;i++)
{
one->enqueue(two->extractMin());
}
}
return one;
}
The swap function is called like this
one->merge(one, two);
Passing it the these two objects to merge
PQueue *one = PQueue::createPQueue(PQueue::UnsortedVector);
PQueue *two = PQueue::createPQueue(PQueue::UnsortedVector);
In your case pointers are completely unnecessary. You can simply use references.
It is also unnecessary to pass in the argument on which the member function is called. You can get the object on which a member function is called with the this pointer.
/// Merge this with other.
void VectorPQueue::merge(VectorPQueue& other) {
// impl
}
In general: Implementing containers with inheritance is not really the preferred style. Have a look at the standard library and how it implements abstractions over sequences (iterators).
At first sight, I cannot see any pointer-related problems. Although I'd prefer to use references instead, and make merge a member function of VectorPQueue so I don't have to pass the first argument (as others already pointed out). One more thing which confuses me is the check for one->size() != 0 - what would be the problem if one is empty? The code below would still correctly insert two into one, as it depends only on two's size.
Regarding deletion of two:
that would be the client´s task, not the implementer
Well, it's up to you how you want do design your interface. But since the function only adds two's elements to one, I'd say it should not delete it. Btw, I think a better name for this method would be addAllFrom() or something like this.
Regarding pointers in general:
I strongly suggest you take a look into smart pointers. These are a common technique in C++ to reduce memory management effort. Using bare pointers and managing them manually via new/delete is very error-prone, hard to make strongly exception-safe, will almost guarantee you memory leaks etc. Smart pointers on the other hand automatically delete their contained pointers as soon as they are not needed any more. For illustrative purposes, the C++ std lib has auto_ptr (unique_ptr and shared_ptr if your compiler supports C++ 11). It's used like this:
{ // Beginning of scope
std::auto_ptr<PQueue> one(PQueue::createPQueue(PQueue::UnsortedVector));
// Do some work with one...:
one->someFunction();
// ...
} // End of scope - one will automatically be deleted
My personal rules of thumb: Only use pointers wrapped in smart pointers. Only use heap allocated objects at all, if:
they have to live longer than the scope in which they are created, and a copy would be too expensive (C++ 11 luckily has move semantics, which eliminate a lot of such cases)
I have to call virtual functions on them
In all other cases, I try to use stack allocated objects and STL containers as much as possible.
All this might seem a lot at first if you're starting with C++, and it's totally ok (maybe even necessary) to try to fully understand pointers before you venture into smart pointers etc.. but it saves a lot of time spend debugging later on. I'd also recommend reading a few books on C++ - I was actually thinking I understood most of C++, until I read my first book :)

shared_ptr with vector

I currently have vectors such as:
vector<MyClass*> MyVector;
and I access using
MyVector[i]->MyClass_Function();
I would like to make use of shared_ptr. Does this mean all I have to do is change my vector to:
typedef shared_ptr<MyClass*> safe_myclass
vector<safe_myclass>
and I can continue using the rest of my code as it was before?
vector<shared_ptr<MyClass>> MyVector; should be OK.
But if the instances of MyClass are not shared outside the vector, and you use a modern C++11 compiler, vector<unique_ptr<MyClass>> is more efficient than shared_ptr (because unique_ptr doesn't have the ref count overhead of shared_ptr).
Probably just std::vector<MyClass>. Are you
working with polymorphic classes or
can't afford copy constructors or have a reason you can't copy and are sure this step doesn't get written out by the compiler?
If so then shared pointers are the way to go, but often people use this paradigm when it doesn't benefit them at all.
To be complete if you do change to std::vector<MyClass> you may have some ugly maintenance to do if your code later becomes polymorphic, but ideally all the change you would need is to change your typedef.
Along that point, it may make sense to wrap your entire std::vector.
class MyClassCollection {
private : std::vector<MyClass> collection;
public : MyClass& at(int idx);
//...
};
So you can safely swap out not only the shared pointer but the entire vector. Trade-off is harder to input to APIs that expect a vector, but those are ill-designed as they should work with iterators which you can provide for your class.
Likely this is too much work for your app (although it would be prudent if it's going to be exposed in a library facing clients) but these are valid considerations.
Don't immediately jump to shared pointers. You might be better suited with a simple pointer container if you need to avoid copying objects.

Dynamically allocated list in C++

I made a cute generic (i.e. template) List class to handle lists in C++. The reason for that is that I found the std::list class terribly ugly for everyday use and since I constantly use lists, I needed a new one. The major improvement is that with my class, I can use [] to get items from it. Also, still to be implemented is an IComparer system to sort things.
I'm using this List class in OBJLoader, my class that loads Wavefront .obj files and converts them to meshes. OBJLoader contains lists of pointers to the following "types": 3D positions, 3D normals, uv texture coordinates, vertices, faces and meshes. The vertices list has objects that must be linked to some objects in all of the 3D positions, 3D normals and uv texture coordinates lists. Faces link to vertices and meshes link to faces. So they are all inter-connected.
For the sake of simplicity, let's consider that, in some context, there are just two lists of pointers: List<Person*> and List<Place*>. Person class contains, among others, the field List<Place*> placesVisited and the Place class contains the field List<Person*> peopleThatVisited. So we have the structure:
class Person
{
...
public:
Place* placeVisited;
...
};
class Place
{
...
public:
List<People*> peopleThatVisited;
};
Now we have the following code:
Person* psn1 = new Person();
Person* psn2 = new Person();
Place* plc1 = new Place();
Place* plc2 = new Place();
Place* plc2 = new Place();
// make some links between them here:
psn1->placesVisited.Add(plc1, plc2);
psn2->placesVisited.Add(plc2, plc3);
// add the links to the places as well
plc1->peopleThatVisited.Add(psn1);
plc2->peopleThatVisited.Add(psn1, psn2);
plc3->peopleThatVisited.Add(plc3);
// to make things worse:
List<Person*> allThePeopleAvailable;
allThePeopleAvailable.Add(psn1);
allThePeopleAvailable.Add(psn2);
List<Place*> allThePlacesAvailable;
allThePlacesAvailable.Add(plc1);
allThePlacesAvailable.Add(plc2);
allThePlacesAvailable.Add(plc3);
All done. What happens when we reach }? All the dtors are called and the program crashes because it tries to delete things two or more times.
The dtor of my list looks like this:
~List(void)
{
cursor = begin;
cursorPos = 0;
while(cursorPos < capacity - 1)
{
cursor = cursor->next;
cursorPos++;
delete cursor->prev;
}
delete cursor;
}
where Elem is:
struct Elem
{
public:
Elem* prev;
T value;
Elem* next;
};
and T is the generic List type.
Which brings us back to the question: What ways are there to safely delete my List classes? The elements inside may or may not be pointers and, if they are pointers, I would like to be able, when I delete my List, to specify whether I want to delete the elements inside or just the Elem wrappers around them.
Smart pointers could be an answer, but that would mean that I can't have a List<bubuType*>, but just List<smart_pointer_to_bubuType>. This could be ok, but again: declaring a List<bubuType*> would cause no error or warning and in some cases the smart pointers would cause some problems in the implementation: for example, I might want to declare a List<PSTR> for some WinAPI returns. I think getting those PSTR inside smart pointers would be an ugly job. Thus, the solution I'm looking for I think should be somehow related to the deallocation system of the List template.
Any ideas?
Without even looking at your code, I say: scrap it!
C++ has a list class template that's about as efficient as it gets, well-known to all C++ programmers, and comes bug-free with your compiler.
Learn to use the STL.1 Coming from other OO languages, the STL might seem strange, but there's an underlying reason for its strangeness, an alien beauty combining abstraction and performance - something considered impossible before Stepanov came and thought up the STL.
Rest assured that you are not the only one struggling with understanding the STL. When it came upon us, we all struggled to grasp its concepts, to learn its particularities, to understand how it ticks. The STL is a strange beast, but then it manages to combine two goals everybody thought could never be combined, so it's allowed to seem unfamiliar at first.
I bet writing your own linked list class used to be the second most popular indoor sport of C++ programmers - right after writing your own string class. Those of us who had been programming C++ 15 years ago nowadays enjoy ripping out those bug-ridden, inefficient, strange, and unknown string, list, and dictionary classes rotting in old code, and replacing it with something that is very efficient, well-known, and bug-free. Starting your own list class (other than for educational purposes) has to be one of the worst heresies.
If you program in C++, get used to one of the mightiest tools in its box as soon as possible.
1Note that the term "STL" names that part of the C++ standard library that stems from Stepanov's library (plus things like std::string which got an STL interface attached as an afterthought), not the whole standard library.
The best answer is that you must think on the lifetime of each one of the objects, and the responsibility of managing that lifetime.
In particular, in a relation from people and the sites they have visited, most probably neither of them should be naturally made responsible for the lifetime of the others: people can live independently from the sites that they have visited, and places exists regardless of whether they have been visited. This seems to hint that the lifetime of both people and sites is unrelated to the others, and that the pointers held are not related to resource management, but are rather references (not in the C++ sense).
Once you know who is responsible for managing the resource, that should be the code that should delete (or better hold the resource in a container or suitable smart pointer if it needs to be dynamically allocated), and you must ensure that the deletion does not happen before the other objects that refer to the same elements finish with them.
If at the end of the day, in your design ownership is not clear, you can fall back to using shared_ptr (either boost or std) being careful not to create circular dependencies that would produce memory leaks. Again to use the shared_ptrs correctly you have to go back and think, think on the lifetime of the objects...
Always, always use smart pointers if you are responsible for deallocating that memory. Do not ever use raw pointers unless you know that you're not responsible for deleting that memory. For WinAPI returns, wrap them into smart pointers. Of course, a list of raw pointers is not an error, because you may wish to have a list of objects whose memory you do not own. But avoiding smart pointers is most assuredly not a solution to any problem, because they're a completely essential tool.
And just use the Standard list. That's what it's for.
In the lines:
// make some links between them here:
psn1->placesVisited.Add(plc1, plc2);
psn2->placesVisited.Add(plc2, plc3);
// add the links to the places as well
plc1->peopleThatVisited.Add(psn1);
plc2->peopleThatVisited.Add(psn1, psn2);
plc3->peopleThatVisited.Add(plc3);
You have instances on the heap that contain pointers to each others. Not only one, but adding the same Place pointer to more than one person will also cause the problem (deleting more than one time the same object in memory).
Telling you to learn STL or to use shared_ptr (Boost) can be a good advice, however, as David Rodríguez said, you need to think of the lifetime of the objects. In other words, you need to redesign this scenario so that the objects do not contain pointers to each other.
Example: Is it really necessary to use pointers? - in this case, and if you require STL lists or vectors, you need to use shared_ptr, but again, if the objects make reference to each other, not even the best shared_ptr implementation will make it.
If this relationship between places and persons is required, design a class or use a container that will carry the references to each other instead of having the persons and places point at each other. Like a many-to-many table in a RDBMS. Then you will have a class/container that will take care of deleting the pointers at the end of the process. This way, no relations between Places and Persons will exist, only in the container.
Regards, J. Rivero
Without looking the exact code of the Add function, and the destructor of your list, it's hard to pin point the problem.
However, as said in the comments, the main problem with this code is that you don't use std::list or std::vector. There are proven efficient implementations, which fit what you need.
First of all, I would certainly use the STL (standard template library), but, I see that you are learning C++, so as an exercise it can be nice to write such a thing as a List template.
First of all, you should never expose data members (e.g. placeVisited and peopleThatVisited). This is a golden rule in object oriented programming. You should use getter and setter methods for that.
Regarding the problem around double deletion: the only solution is having a wrapper class around your pointers, that keeps track of outstanding references. Have a look at the boost::shared_ptr. (Boost is another magnificent well-crafted C++ library).
The program crashes because delete deallocates the memory of the pointer it is given it isn't removing the items from you list. You have the same pointer in at least two lists, so delete is getting called on the same block of memory multiple times this causes the crash.
First, smart pointers are not the answer here. All they will do is
guarantee that the objects never get deleted (since a double linked list
contains cycles, by definition).
Second, there's no way you can pass an argument to the destructor
telling it to delete contained pointers: this would have to be done
either via the list's type, one of its template arguments, partial
specialization or an argument to the constructor. (The latter would
probably require partial specialization as well, to avoid trying to
delete a non-pointer.)
Finally, the way to not delete an object twice is to not call delete on
it twice. I'm not quite sure what you thing is happening in your
destructor, but you never change cursor, so every time through, you're
deleting the same two elements. You probably need something more along
the lines of:
while ( cursor not at end ) {
Elem* next = cursor->next;
delete cursor;
cursor = next;
}
--
James Kanze
And you could easily implement [] around a normal list:
template <class Type>
class mystdlist : public std::list<Type> {
public:
Type& operator[](int index) {
list<Type>::iterator iter = this.begin();
for ( int i = 0; i < index; i++ ) {
iter++;
}
return *iter;
}
};
Why you would want to do this is strange, IMHO. If you want O(1) access, use a vector.

Confusion concerning boost::shared_ptr

My question revolves around whether or not I must expose my use of the boost::shared_ptr from my interface and whether or not I should expose raw pointers or references from my interface.
Consider the case of a Person who has an Employeer. Employeer internally maintains all of its employees in a vector< shared_ptr< Person > >. Because of this, do best practices dictate that any interface involving Person should be a shared_ptr wrapped person?
For example, are all or only some of these ok:
Person Employeer::getPresidentCopy();
Person& Employeer::getPresidentRef();
Person* Employeer::getPresidentRawPtr();
shared_ptr<Person> Employeer::getPresidentSharedPtr();
Or for example:
void Employeer::hireByCopy(Person p);
void Employeer::hireByRef(Person& p);
void Employeer::hireByRawPtr(Person* p);
void Employeer::hireBySharedPtr(shared_ptr<Person> p);
If I later want to change the implementation to use johns_very_own_shared_ptr instead of the boost variety, am I trapped in the old implementation?
On the other hand, if I expose raw pointers or references from the interface, do I risk someone deleting the memory out from under the shared_ptr? Or do I risk the shared_ptr being deleted and making my reference invalid?
See my new question for an example involving this.
For example, are all or only some of these ok:
It depends on what you're trying to accomplish. Why does the vector hold shared_ptrs instead of just directly storing Person s by value? (And have you considered boost::ptr_vector?)
You should also consider that maybe what you really ought to hand out is a weak_ptr.
If I later want to change the implementation to use johns_very_own_shared_ptr instead of the boost variety, am I trapped in the old implementation?
Pretty much, but it's not impossible to fix. (I suspect that in C++0x, liberal use of the auto keyword will make this easier to deal with, since you won't have to modify the calling code as much, even if it didn't use typedef s.) But then, why would you ever want to do that?
On the other hand, if I expose raw pointers or references from the interface, do I risk someone deleting the memory out from under the shared_ptr?
Yes, but that's not your problem. People can extract a raw pointer from a shared_ptr and delete it, too. But if you want to avoid making things needlessly unsafe, don't return raw pointers here. References are much better because nobody ever figures they're supposed to delete &reference_received_from_api;. (I hope so, anyway ^^;;;; )
I would introduce a typedef and insulate myself against changes. Something like this:
typedef std::shared_ptr<Person> PersonPtr;
PersonPtr Employeer::getPresident() const;
I place typedefs like this one in a (just one) header together with forward declarations. This makes it easy to change if I would ever want to.
You don't have to hand out shared_ptr, but if you hand out raw pointers you run the risk of some raw pointer persisting after the object has been destroyed.
With fatal consequences.
So, handing out references generally OK (if client code takes address then that's no more your fault than if client code takes address of *shared_ptr), but raw pointers, think first.
Cheers & hth.,
I shouldn't give user raw pointers, when you use shared_ptrs. User could delete it, what will cause double deletion.
To hide usage of boost:shared_ptr you can use typedef to hide actual type, and use this new type instead.
typedef boost::shared_ptr<Person> Person_sptr;
The only reason to hand out a shared_ptr here is if the lifetime of the returned object reference is not tied directly to the lifetime of its residence in the vector.
If you want somebody to be able to access the Person after they stop being an Employee, then shared_ptr would be appropriate. Say if you are moving the Person to the vector for a different Employer.
I work on a moderately sized project that links in several libraries. Some of those libraries have their own memory management subsystems (APR, MFC) and really annoy me. Whether their view of the world is good or bad, it's entirely different from everybody else's and requires a little more code than they otherwise would.
Additionally, those libraries make swapping out malloc or new with jemalloc or the Boehm-Demers-Weiser garbage collector much harder (on Windows it's already hard enough).
I use shared pointers a lot in my own code, but I prefer not to tell others how to manage their memory. Instead, hand out objects whenever possible (letting the library user decide when and how to allocate the memory), and when it's not possible do one of:
hand out raw pointers (plus either a promise that the pointers can be deleted or a Destroy() function to call to deallocate the objects)
accept a function or STL allocator-like argument so you can hook into whatever the user's using for memory management (feel free to default to new and std::allocator)
have your library users hand you allocated memory buffers (like std::vectors)
Using this kind of library doesn't have to be nasty:
// situation (1) from above
std::shared_ptr<Foo> foo(Library_factory::get_Foo(), Library_factory::deallocate);
// situation (2) above (declaration on next line is in a header file)
template<typename allocator=std::allocator<Foo> > Foo* library_function_call();
boost::shared_ptr<Foo> foo = library_function_call();
// situation (3) above, need to fill a buffer of ten objects
std::vector<Foo> foo_buffer(10);
fill_buffer(&foo_buffer[0], foo_buffer.size());

STL erase-remove idiom vs custom delete operation and valgrind

This is an attempt to rewrite some old homework using STL algorithms instead of hand-written loops and whatnot.
I have a class called Database which holds a Vector<Media *>, where Media * can be (among other things) a CD, or a Book. Database is the only class that handles dynamic memory, and when the program starts it reads a file formatted as seen below (somewhat simplified), allocating space as it reads the entries, adding them to the vector (v_) above.
CD
Artist
Album
Idnumber
Book
Author
Title
Idnumber
Book
...
...
Deleting these object works as expected when using a hand-written loop: EDIT: Sorry I spoke too soon, it's not actually a 'hand-written' loop per-se.. I've been editing the project to remove hand-written loops and this actually uses the find_if algorithm and a manual deletion, but the question is till valid. /EDIT.
typedef vector<Media *>::iterator v_iter;
...
void Database::removeById(int id) {
v_iter it = find_if(v_.begin(), v_.end(), Comparer(id));
if (it != v_.end()) {
delete *it;
v_.erase(it);
}
}
That should be pretty self-explanatory - the functor returns true if it find an id matching the parameter, and the object is destroyed. This works and valgrind reports no memory leaks, but since I'd like to use the STL, the obvious solution should be to use the erase-remove idiom, resulting in something like below
void Database::removeById(int id) {
v_.erase(remove_if(v_.begin(), v_.end(), Comparer(id)), v_.end());
};
This, however, 'works' but causes a memory leak according to valgrind, so what gives? The first version works fine with no leaks at all - while this one always show 3 allocs 'not freed' for every Media object I delete.
The rule is: if you apply remove() on a vector that contains and is the owner of pointers you leak memory.
There is a nice solution in "Effective STL", by Scott Meyers. And it involves no smart pointers! Using smart pointers only to make erase-remove work is an overkill.
Here it is (from the book, Item 33). The task is to selectively remove from a vector widgets for which isCertified() returns false.
class Widget
{
public:
isCertified() const;
...
};
void delAndNullifyUncertified(Widget*& pWidget)
{
if (!pWidget->isCertified())
{
delete pWidget;
pWidget = 0;
}
}
vector<Widget *> v;
v.push_back(new Widget);
...
// set to NULL all uncertified widgets
for_each(v.begin(), v.end(), delAndNullifyUncertified);
// eliminate all NULL pointers from v
v.erase(remove(v.begin(), v.end(), static_cast<Widget *>(0)),
v.end();
I hope this helps.
edit (August 28th, 2012): to reflect a valid observation from Slavik81
This is why you should always, ALWAYS use smart pointers. The reason that you have a problem is because you used a dumb pointer, removed it from the vector, but that didn't trigger freeing the memory it pointed to. Instead, you should use a smart pointer that will always free the pointed-to memory, where removal from the vector is equal to freeing the pointed-to memory.
In the first version, you're carefully calling delete *it. In the updated version, you're not.... v_.erase is de-allocating the pointer, but not the object the pointer references.
You already have a specific answer. However, your underlying problem is that you're using naked pointers to manually manage resources. That is hard, and sometimes it hurts.
Change your type to std::vector<std::shared_ptr<Media> > and things become much easier.
(If your compiler doesn't yet support std::shared_ptr, it will very likely have std::tr1::shared_ptr. Otherwise use boost's boost::shared_ptr.)
There is no call to delete in the second version of removeById. Erasing an element from a vector of pointers doesn't call delete on the pointer.
The erase-remove version presented is roughly equivalent to using the original removeById, but with a small change:
void Database::removeById(int id) {
v_iter it = find_if(v_.begin(), v_.end(), Comparer(id));
if (it != v_.end()) {
//delete *it;
v_.erase(it);
}
}
Hopefully this makes it clearer what's going on, and why the leaks are appearing.
Obviously your vector OWNS the objects it contains.
As you noticed the STL containers are not OO-friendly in the sense that they do not easily adapt to inheritance. You need to use dynamically allocated memory and all its woes for that.
The first and easy solution is to replace plain pointers (please, no more) by smart pointers. People will usually recommend shared_ptr, but if you have access to C++0x prefer them unique_ptr.
There is also another solution that you should considerate. Containers that mimicks the STL ones but have been designed to work with inheritance hierarchy. They use pointers under the hood (obviously) but relieves you of the tedium of managing the memory yourself and the overhead associated with smart pointers (especially shared_ptr).
Behold the Boost Pointer Container library!
It is clearly here the best solution, for it has been created exactly for the problem you are trying to solve.
Furthermore, its containers are (mostly I think) STL compliant, so you'll be able to use the erase/remove idiom, the find_if algorithm, etc...
This means that the second version is incorrect. If you want to use it, consider shared_ptr:
typedef vector< shared_ptr<Media> > MediaVector;
...