ablimit
ablimit

Reputation: 2361

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 ?

Upvotes: 4

Views: 1633

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279385

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

Upvotes: 3

je4d
je4d

Reputation: 7848

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.

Upvotes: 3

Related Questions