views:

92

answers:

3
//Using g++ and ubuntu.
#include <vector>
using namespace std;

Define a class:

class foo(){
(...)
foo(int arg1, double arg2);
}

Constructor:

foo::foo(int arg1, double arg2){ 
(...) //arrays whose length depend upon arg1 and arg2
} 

I would like to do something like this:

vector<foo> bar(10); //error: no matching function for call to 'foo::foo()'
bar[0] = new foo(123, 4.56);
(...)

An alternative method (which I like less) is to use push_back:

vector<foo> bar; //works
bar.push_back(new foo(123, 4.56)); //throws similar error.
//Omitting the "new" compiles but throws a "double free or corruption (fasttop)" on runtime.

I want different elements of the vector to be constructed differently, so I don't want to use the "Repetitive sequence constructor". What should be done?

+3  A: 
GMan
+1 for a really good answer. If I could, I would like to give an additional +1 for not saying that you should always use std::vector, but that you should always use a vector.
Simon
A: 

std::vector always create elements based on the default constructor which you haven't define in snippet above.

the push_back method is facing a double free issue because you did not handle the copy constructor.

YeenFei
+1  A: 
vector<foo> bar(10); //error: no matching function for call to 'foo::foo()'

This is failing because the std::vector constructor you're calling is

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

As you can see, it is trying to fill the vector with 10 calls to the default constructor of foo which does not exist.

Also, all your examples featuring new will fail because the vector is expecting an object of type foo, not foo *. Furthermore, changing to vector<foo *> will fail too unless you manually delete every member before clearing the vector. If you really want to go the dynamic memory allocation route create a vector< shared_ptr< foo > >. shared_ptr is available in the Boost libraries or if your compiler includes TR1 libraries it'll be present in the <memory> header within the std::tr1 namespace or if your compiler has C++0x libraries it'll be available in the std namespace itself.

What you should probably do is the following:

vector<foo> bar;
bar.reserve(10);
bar.push_back( foo( 1, 2 ) );
...
...
bar.push_back( foo( 10, 20 ) ); //10 times
Praetorian
Probably should mention that shared_ptr is a part of the boost libraries or C++0x
Chris
This alone does not work, but I need to have the big 3.
Kevin Kostlan
@Kevin: I suspect you should use `std::vector` so you don't. Do factor resource from usage, do not do both.
GMan
@Chris, good call; I've edited to answer accordingly.
Praetorian