在容器之间移动对象而无需复制开销
我有一个对象指针的全局向量,我正在生成相同类型的对象并将它们放入 forloop 内的向量中。 那是:
vector<object * > ptrVector;
vector<object > objVector;
for ( ; ;)
{
getElements(objVector);
calcualte_with(objVector);
objVector.clear();
}
我的问题是如何在不复制开销的情况下将 objVector 中的对象“移动”到 ptrVector 中?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,C++98/C++03 做不到。 objVector 中的对象由 objVector 分配和拥有,当您破坏或清除它时,这些项目也将被破坏。
使用 C++11,您可以为对象实现移动构造函数,并使用从 objVector 中的对象移动构造的新对象填充 ptrVector。一般来说,移动构造函数会移动对象的私有成员,避免复制该对象拥有的任何大型堆分配数据结构,这通常非常便宜。
为此,您可以使用 std::transform(begin(objVector), end(objVector), std::back_inserter(ptrVector), [](object& o){return new object(std: :move(o);})
但是,我建议将 ptrVector 设为
std::vector>
或std::vector>
而不是使用原始指针,如果ptrVector
分别拥有其所指向的对象的独占或共享所有权。In short, you can't with C++98/C++03. The objects in objVector are allocated and owned by objVector, and when you destruct or clear it the items will also be destructed.
With C++11, you could implement a move constructor for your object and fill ptrVector with new objects that have been move-constructed from the objects in objVector. In general, move constructors move the private members of the object over, avoiding a copy of any large heap-allocated data structure that are owned by the object, which is usually very cheap.
To do that, you'd use something like
std::transform(begin(objVector), end(objVector), std::back_inserter(ptrVector), [](object& o){return new object(std::move(o);})
However, I'd recommend making ptrVector a
std::vector<std::unique_ptr<object>>
orstd::vector<std::shared_ptr<object>>
instead of using a raw pointer ifptrVector
has exclusive or shared ownership of the objects pointed to by it respectively.简短的回答 - 你不能。
ptrVector
包含指针,而不是object
的实例,因此无论有或没有复制开销,通过移动它们或其他方式,对象永远不能位于其中。如果
objVector
本身首先与 or 交换(在C++11) 移至vector
Short answer - you can't.
ptrVector
contains pointers, not instances ofobject
, so the objects cannot ever be "in" it, by moving them or otherwise, with or without copy overhead.Objects that are "in"
objVector
can only live beyondclear()
being called on the vector ifobjVector
itself is first swapped with or (in C++11) moved to another instance ofvector<object>
.