[英]move objects between containers without copying overhead
I have a global vector of object pointers and I'm generating same type of objects and putting them into vector inside a forloop. 我有一个对象指针的全局向量,我正在生成相同类型的对象,并将它们放入forloop内的向量中。 That is: 那是:
vector<object * > ptrVector;
vector<object > objVector;
for ( ; ;)
{
getElements(objVector);
calcualte_with(objVector);
objVector.clear();
}
My questions is how can I "move" objects in objVector into the ptrVector without copying overhead ? 我的问题是如何在不复制开销的情况下将objVector中的对象“移动”到ptrVector中?
In short, you can't with C++98/C++03. 简而言之,你不能用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. objVector中的对象由objVector分配和拥有,当您破坏或清除它时,项目也将被破坏。
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. 使用C ++ 11,您可以为对象实现移动构造函数,并使用从objVector中的对象移动构造的新对象填充ptrVector。 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);})
要做到这一点,你可以使用类似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>>
or std::vector<std::shared_ptr<object>>
instead of using a raw pointer if ptrVector
has exclusive or shared ownership of the objects pointed to by it respectively. 但是,如果ptrVector
具有独占或共享所有权,我建议将ptrVector设为std::vector<std::unique_ptr<object>>
或std::vector<std::shared_ptr<object>>
而不是使用原始指针。它分别指向的对象。
Short answer - you can't. 简短的回答 - 你不能。
ptrVector
contains pointers, not instances of object
, so the objects cannot ever be "in" it, by moving them or otherwise, with or without copy overhead. ptrVector
包含指针,而不是object
实例,因此对象不能通过移动它们或其他方式“进入”它,有或没有复制开销。
Objects that are "in" objVector
can only live beyond clear()
being called on the vector if objVector
itself is first swapped with or (in C++11) moved to another instance of vector<object>
. 如果首先交换objVector
本身或者(在C ++ 11中)移动到vector<object>
另一个实例,那么“in” objVector
对象只能在向量上调用clear()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.