tags:

views:

109

answers:

4

In c++, is using a vector of objects a good idea? If not, what's wrong with this c++ code?

#include <vector>

using namespace std;

class A {};

int main() {

        vector<A*> v ( new A);
        return 0;
}

from g++:

13: error: invalid conversion from A*' tounsigned int'

+11  A: 

The constructor for std::vector takes an initial length, not an element.

This means you'd normally do:

vector<A*> v(1); // Initialize to length 1
v.push_back( new A() ); // Add your element...

You're getting the compiler error you are because, on your system, size_type is defined as an unsigned int. It's trying to use that constructor, but failing, since you're passing it a pointer to an A.

Reed Copsey
+4  A: 

You need to read the documentation before using something you don't know.

Here are the different constructors for the std::vector class:

explicit vector ( const Allocator& = Allocator() );
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
template <class InputIterator>
         vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
vector ( const vector<T,Allocator>& x );
Bertrand Marron
+2  A: 

Vector doesn't have a constructor that takes one item to store.

To make a vector of one item with the given value:

vector<A*> v ( 1, new A);

As to whether it is a good idea to have a vector of pointers to dynamically allocated objects - no. You have to manage that memory manually.

It's much better to store objects by value, or if you must - use a smart pointer to automate managing memory (e.g std::tr1::shared_ptr).

UncleBens
+1  A: 

I would recommend not using std::vector like this: memory management becomes a nightmare. (For example, vector<A*> v ( 10, new A); has ten pointers but only one allocated object, and you have to remember to deallocate only once. If you don't deallocate at all, you have unfreed memory.)

Instead, consider using the Boost Pointer Container library: you can pass in newly allocated objects, and it will handle all of the memory management for you.

Seth Johnson