简体   繁体   中英

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. 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 ?

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>> 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.

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.

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM