Move objects between containers without copying overhead

I have a global vector of object pointers, and I create objects of the same type and put them in a vector inside forloop. I.e:

vector<object * > ptrVector; vector<object > objVector; for ( ; ;) { getElements(objVector); calcualte_with(objVector); objVector.clear(); } 

My questions are: how can I "move" objects in objVector to ptrVector without copying overhead?

+4
source share
2 answers

In short, you cannot use C ++ 98 / C ++ 03. Objects in objVector are allocated and owned by objVector, and when you destroy or clean it, objects will also be destroyed.

With C ++ 11, you can implement a move constructor for your object and populate ptrVector with new objects that were moved along the way from objects to objVector. In general, move constructors move private members of an object, avoiding a copy of any large data structure distributed by the heap that belong to the object, which is usually very cheap.

To do this, you should use something like std::transform(begin(objVector), end(objVector), std::back_inserter(ptrVector), [](object& o){return new object(std::move(o);})

However, I 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 joint ownership of the objects to which it indicates accordingly.

+3
source

The short answer is you cannot.

ptrVector contains pointers, not instances of an object , so objects can never "be" in it, moving them in any other way with or without overhead.

Objects that are "in" objVector can go beyond clear() , which are called on the vector if objVector itself was first replaced or (in C ++ 11) transferred to another instance of vector<object> .

+3
source

Source: https://habr.com/ru/post/1395950/


All Articles