I am in a rather specific situation that requires me to use a vector of raw pointers as a class member:
- I need to keep a list of abstract objects (I understood I could not use
vector<AbstractClass>
directly). - I can't use Boost or std::tr1, so no smart pointer library (because of constraints from the hardware I'm using).
Here is a basic example of what I need:
#include <vector>
class Foo
{
virtual void foo() {}
};
class Bar : public Foo
{
void foo(){}
};
class FooBar
{
vector<Foo*> list;
void add(){ list.push_back(new Bar()); }
};
Coming from Java, I am very scared of pointers and memory leaks. This post initially suggests to delete the objects manually when the object goes out of scope. Is it enough to do this in the destructor of FooBar
?
class FooBar
{
vector<Foo*> list;
void add(){ list.push_back(new Bar()); }
~FooBar(){
for(vector<Foo*>::iterator it=list.begin(); it!=list.end(); it++)
delete *it;
}
};
By the rule of three, I guess I also have to implement a copy constructor and an assignment operator. Is the following (based on this and that posts) a correct implementation ?
FooBar::FooBar(const FooBar& orig) : list(orig.list.size()) {
try {
vector<Foo*>::iterator thisit = list.begin();
vector<Foo*>::const_iterator thatit = orig.list.cbegin();
for (; thatit != orig.list.cend(); ++thisit, ++thatit)
*thisit = *thatit; // I'm okay with a shallow copy
} catch (...) {
for (vector<Foo*>::iterator i = list.begin(); i != list.end(); ++i)
if (!*i)
break;
else
delete *i;
throw;
}
}
FooBar& operator=(const FooBar& orig){
FooBar tmp(orig);
swap(tmp);
return *this;
}