I would like to ask a general advise. The code below fully compiles and roughly represents the structure of the code i deal with. In a nutshell i want to pass a series of objects derived from the based class (Class1) and some other parameters from one place to another. More precisely, implement different child classes of the parent class, gather instances of those and pass for processing with parameters.
The question is, would you recommend to use a vector of objects or vector of pointers? I don't mind going for some new stuff from C++11
(std::unique_ptr
, std::shared_ptr
) if this is better/safer/less memory leaks/etc for some reason. I would really appreciate if someone could arguably advise on container for such a case and/or provide an example using C++11
.
p/s/ here UncleBens said that using pointers could lead to memory leaks if/when exceptions are thrown. So maybe i should really use smart pointers for the task? How would this look?
p/p/s/ funny enough, the real life example gives me Bus error: 10 when i try to use those Class2
objects from std::vector< Container<d>*> / std::vector< Container<d>>
. However, i'm not able to reproduce the error in a simple case...
#include <string>
#include <iostream>
#include <vector>
template<int dim>
class Class1 {
public:
Class1() {};
~Class1() {};
};
template<int dim>
class Class2 : public Class1<dim>
{
public:
Class2() :
Class1<dim>() {};
};
template <int dim>
class Container
{
public:
Container( Class1<dim> & f, int param1) : c1(f), param_(param1) {}
Class1<dim> & c1;
int param_;
};
static const int d = 2;
int main()
{
int p = 1;
Class2<d> c2;
std::vector< Container<d> *> p_list;
std::vector< Container<d> > list;
{
p_list.push_back ( new Container<d> ( c2,p ) );
}
std::cout<<"from pointers: "<<p_list[0]->param_<<std::endl;
{
list.push_back( Container<d> ( c2,p ) );
}
std::cout<<"from objects: "<<list[0].param_<<std::endl;
}