0

Consider that I have a pseudo code like

std::vector< Something > myVector;

while (someCondition) {
    // Populate vector

    functionThatNeedsCopyOfVector(myVector);
    myVector.clear()
};

The key point is that this snippet fulfills the pattern of "reusing" the same vector object multiple times where it always fills it up with a few elements and then passes a copy of the vector somewhere, before clearing it and starting all over again.

Thinking about this I though that in principle it should be possible to optimize this snippet to

std::vector< Something > myVector;

while (someCondition) {
    // Populate vector

    functionThatNeedsCopyOfVector(std::move(myVector));
};

(Assuming there is an overload of functionThatNeedsCopyOfVector that accepts rvalue references instead)

However this would clearly be a case of use-after-move which is UB (per se). However I was wondering whether the standard might dictate how vector's move constructor behaves exactly and if that would for instance contain something that would make the original vector equal to a freshly constructed vector (because the internal data structure was moved)?

If there was such a guarantee, then the "move-snippet" should not be UB, right?

And in case it is indeed UB: Is there a pattern that could be used instead that avoids the (seemingly) unneeded copy when one is to clear it afterwards anyways?

Raven
  • 2,951
  • 2
  • 26
  • 42
  • 2
    Keep both. `std::move` to give the function the opportunity to take ownership of the elements and avoid a copy, and `clear` to guarantee the state of the vector at the end of each iteration, ready to be repopulated. – François Andrieux May 10 '21 at 15:43
  • 3
    `Unless otherwise specified, all standard library objects that have been moved from are placed in a "valid but unspecified state", meaning the object's class invariants hold (so functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from):` from https://en.cppreference.com/w/cpp/utility/move – Mike Vine May 10 '21 at 15:43
  • Why is the vector created outside of the loop? Looks like making a new vector each iteration and moving from it would be better. Also, use after move is not UB. – super May 10 '21 at 15:47
  • Thank you all for your comments. I guess my understanding of use-after-move was just wrong – Raven May 10 '21 at 15:51

0 Answers0