如何使用唯一对象调整 std::vector 的大小
我有一个对象向量。每个对象都有一个不可复制对象(boost::signal
)的boost::shared_ptr
。该对象的默认构造函数创建 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能想到的唯一方法是使用
reserve
使向量分配您需要的内存(正如@Jonathan 回答的那样)。您可以将generate_n
与std::back_inserter
一起使用来添加元素:此方法不需要
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 usegenerate_n
with anstd::back_inserter
to add the elements:The
reserve
is not necessary with this approach, although it is probably faster ifn
is large.我能想到的最简单的方法是预先保留内存,以便向量只需要一次分配:
然后循环和push_back() 。这还不足以满足您的需求吗?
The simplest way I can think of is to reserve the memory beforehand so that only one allocation is needed by the
vector
:Then loop and
push_back()
. Is that not sufficient for your needs?您是否无法使用实际的复制语义来实现复制构造函数/复制赋值?除非你在矢量填充方面表现出色,否则这似乎是最明显的解决方案。
Are you not able to implement a copy constructor/copy assignment with actual copy semantics? Unless you're having serious performance with the vector filling this seems like the most obvious solution.