Is there a standard container for a sequence of fixed length, where that length is determined at runtime. Preferrably, I\'d like to pass an argument to the constructor of ea
Add a level of indirection by using a std::shared_ptr. The shared pointer can be copied and assigned as usual, but without modifying the object that is pointed to. This way you should not have any problems, as the following example shows:
class a
{
public:
a(int b) : b(b) { }
// delete assignment operator
a& operator=(a const&) = delete;
private:
// const member
const int b;
};
// main
std::vector> container;
container.reserve(10);
container.push_back(std::make_shared(0));
container.push_back(std::make_shared(1));
container.push_back(std::make_shared(2));
container.push_back(std::make_shared(3));
Another advantage is the function std::make_shared which allows you to create your objects with an arbitrary number of arguments.
Edit:
As remarked by MvG, one can also use std::unique_ptr. Using boost::indirect_iterator the indirection can be removed by copying the elements into a new vector:
void A::foo(unsigned n)
{
std::vector> bs_vector;
bs_vector.reserve(n);
for (unsigned i = 0; i != n; ++i)
{
bs_vector.push_back(std::unique_ptr(new B(this, i)));
}
typedef boost::indirect_iterator>::iterator> it;
// needs copy ctor for B
const std::vector bs_vector2(it(bs_vector.begin()), it(bs_vector.end()));
// work with bs_vector2
}