我有一个对象矢量。 每个对象都有一个boost::shared_ptr到一个不可复制的对象(一个boost::signal )。 对象的默认构造函数创建boost :: signal对象。
struct FuncRef { typedef boost::signal0<void, > Func; boost::shared_ptr <Func> function; FuncRef(): function(new Func) { } };要将我的向量设置为包含X个别对象,我这样做了: -
vec.resize(X);这没有达到我的预期,因为它使用默认构造函数来创建一个对象,然后使用复制构造函数来创建重复项。 我最终得到X对象,但它们都指向相同的boost::signal0对象。
有没有比在for循环中使用push_back更简单的方法来构建我的向量?
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?
最满意答案
我能想到的唯一方法是使用reserve来使向量分配你需要的内存(如@Jonathan的回答)。 你可以使用带有std::back_inserter generate_n来添加元素:
FuncRef makeFuncRef() { return FuncRef(); } vec.reserve(vec.size() + n); std::generate(std::back_inserter(vec), n, makeFuncRef);这种方法不需要reserve ,但如果n很大则可能更快。
The only way I can think of is to use reserve to make the vector allocate the memory you need (as @Jonathan answered). You can the use generate_n with an std::back_inserter to add the elements:
FuncRef makeFuncRef() { return FuncRef(); } vec.reserve(vec.size() + n); std::generate(std::back_inserter(vec), n, makeFuncRef);The reserve is not necessary with this approach, although it is probably faster if n is large.
更多推荐
发布评论