I’m not very experienced with C++ yet, so bear with me if this is basic stuff.
I have some code like that below. L is an abstract class (it has a number of pure virtual functions), and A, B and C are regular classes all derived from L. There may be any number of these, and they are all different.
int main() {
// ...
std::vector<L*> ls(3) ;
ls[0] = new A ;
ls[1] = new B ;
ls[2] = new C ;
int i ;
for (i = 0 ; i < ls.size() ; i++) {
if (ls[i]->h()) {
// ...
}
}
// ...
}
It works, but there really has to be a better way to initialise that vector. Right?
The vector is not supposed to change after it has been first initialised. I figure I can’t make it const, however, because the various objects may themselves change internally. I picked a vector over a regular array because I don’t want to manually keep track of its length (that proved error prone).
Ideally I’d like to pull the definition and initialisation of the vector out of main and preferably into a separate file that I can then #include. When I try that the compiler complains that it “expected constructor, destructor, or type conversion before ‘=’ token”. All the classes A, B and C have default constructors.
Also, I was under the impression that I have to manually delete anything created using new, but it won’t delete ls with either delete or delete[]. If I try delete ls; the compiler complains that “type ‘class std::vector<L*, std::allocator<L*> >’ argument given to ‘delete’, expected pointer”.
Is the above even safe or does it cause some memory problems?
I don’t think so, at least not without C++0x. Which way would you prefer? Your initialization code is completely fine.
You can still make the vector itself
const, only its member type cannot be a pointer toconstthen.You don’t have to keep track of the length in constant arrays:
And often you don’t need the size anyway, e.g. with Boost.Range.
That would violate the one-definition rule. You can put the declaration into a header file, but the definition has to go into a source file.
Your impression is correct, but you haven’t created
lswithnew, only its elements. After using the vectors, you have todeleteeach of its elements, but not the vector itself.The recommended alternative to STL containers holding polymorphic pointers is the Boost pointer container library.