user606547
user606547

Reputation:

Vector of object pointers, initialisation

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?

Upvotes: 3

Views: 707

Answers (4)

fredoverflow
fredoverflow

Reputation: 263220

Since you know the size at compile time, I suggest using an array instead of a vector. Using the class template array instead of a C-style array gives you the benefit of a standard container interface, just like a vector. That is, you can call size() on the array and obtain iterators and so on.

And to make sure you don't forget to delete the objects, I suggest using smart pointers:

#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

boost::array<boost::shared_ptr<L>, 3> ls = { {
    boost::make_shared<A>(),
    boost::make_shared<B>(),
    boost::make_shared<C>(),
} };

Modern compilers ship their own versions of array and shared_ptr in the standard library:

#include <array>
#include <memory>

std::array<std::shared_ptr<L>, 3> ls = { {
    std::make_shared<A>(),
    std::make_shared<B>(),
    std::make_shared<C>(),
} };

Note that the outermost braces are technically not needed, but leaving them out might produce compiler warnings, at least that's what happens on my compiler.

Ideally I'd like to pull the definition and initialization of the vector out of main and preferably into a separate file that I can then #include

In that case, you need a header file with a declaration and an implementation file with a definition of ls:

// file ls.h

#ifndef LS_H
#define LS_H

#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>

extern boost::array<boost::shared_ptr<L>, 3> ls;

#endif

// file ls.cpp

#include "ls.h"
#include <boost/make_shared.hpp>

boost::array<boost::shared_ptr<L>, 3> ls = { {
    boost::make_shared<A>(),
    boost::make_shared<B>(),
    boost::make_shared<C>(),
} };

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490338

If C++11 is acceptable, you might be better off with an std::array instead of std::vector:

std::array<L *, 3> = {new A(), new B(), new C()};

Upvotes: 0

Philipp
Philipp

Reputation: 49842

but there really has to be a better way to initialise that vector. Right?

I don't think so, at least not without C++0x. Which way would you prefer? Your initialization code is completely fine.

I figure I can't make it const, however, because the various objects may themselves change internally.

You can still make the vector itself const, only its member type cannot be a pointer to const then.

I picked a vector over a regular array because I don't want to manually keep track of its length (that proved error prone).

You don't have to keep track of the length in constant arrays:

L* ls[] = { new A, new B, new C };
// with <boost/range/size.hpp>
std::size_t num = boost::size(ls);
// without Boost, more error-prone
// std::size_t num = sizeof ls / sizeof ls[0];

And often you don't need the size anyway, e.g. with Boost.Range.

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.

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.

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[].

Your impression is correct, but you haven't created ls with new, only its elements. After using the vectors, you have to delete each of its elements, but not the vector itself.

The recommended alternative to STL containers holding polymorphic pointers is the Boost pointer container library.

Upvotes: 4

GWW
GWW

Reputation: 44131

You do indeed have to use delete on the objects you created. You are calling delete on the vector not the objects. Something like:

for(size_t i = 0; i < ls.size(); i++){
    delete ls[i];
}

For your construction issue you could wrap them into a function and put that function in it's own header file. You would have to make sure to include all of the relevant classes header files as well.

void init_vector(std::vector<LS*> & v){
    ls[0] = new A ; 
    ls[1] = new B ;
    ls[2] = new C ;
}

Upvotes: 1

Related Questions