I have a vector of objects. Each object has a boost::shared_ptr to a noncopyable object (a boost::signal). the object’s default constructor creates the boost::signal object.
struct FuncRef
{
typedef boost::signal0<void, > Func;
boost::shared_ptr <Func> function;
FuncRef():
function(new Func)
{
}
};
To set my vector to contain X individual objects, I did this:-
vec.resize(X);
This didn’t do what I expected, because it uses the default constructor to make one object, and then the copy constructor to make the duplicates. I end up with X objects, but they all point to the same boost::signal0 object.
Is there an easier way of building my vector correctly than just using push_back in a for loop?
The only way I can think of is to use
reserveto make the vector allocate the memory you need (as @Jonathan answered). You can the usegenerate_nwith anstd::back_inserterto add the elements:The
reserveis not necessary with this approach, although it is probably faster ifnis large.