I have a std::vector<std::string>
to be re-used in a loop. Is it ok to std::move
elements out? If I moved the ith element out, then ith slot goes into an undefined but valid state, but what about the vector? Is its state still defined and valid? Also, can I clear()
and then reuse the vector in the next iteration?
EDIT: please read the question before you flag for duplication. I'm asking the state of v2
after doing std::move(v2[0])
, not std::move(v2)
. Also I reuse v2
after I did v2.clear()
. How is that similar to the suggested duplication?
EDIT: code example:
struct Foo { string data; /* other data memebers */ void workOnData(); } std::vector<std::string> buffer; Foo foo; while (1) { buffer.clear(); loadData(buffer); // push data to buffer, at least one element in buffer guaranteed foo.data.assign(std::move(buffer[0])); // please don't ask is Foo necessary or why workOnData has to be a member method. THIS IS A SIMPLIFIED EXAMPLE! foo.workOnData(); }
std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.
std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.
You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap. @R.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
Is it ok to std::move elements out?
Yes, it's okay.
If I moved the ith element out, then ith slot goes into an undefined but valid state
It leaves the element in a valid but unspecified state. The difference between those two words is important in C++, but probably not too important to this question. Just thought I should point it out.
but what about the vector?
The vector is in a valid and well-specified state, though one of its elements is in an unspecified state.
Also, can I clear() and then reuse the vector in the next iteration?
Yes. Of course. Though you can do a lot more than that. Unlike a moved-from vector, you can still count on the vector having the same size, the same capacity, and all elements other than the one you just moved from remaining unchanged. As well as all references and iterators to elements (including the one you just moved from) remaining valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With