In other words is the following code sound(defined behavior,portable,...)
std::vector<int> vec(100,42);
std::vector<int> other = std::move(vec);
vec.resize(0);//is this sound
//using vec like an empty vector
In other words is the following code sound(defined behavior,portable,...)
std::vector<int> vec(100,42);
std::vector<int> other = std::move(vec);
vec.resize(0);//is this sound
//using vec like an empty vector
Yes, it is safe.
From §23.3.6.5:
If
sz <= size()
, equivalent to callingpop_back()
size() - sz
times. Ifsize() < sz
, appendssz - size()
default-inserted elements to the sequence.
So basically, when you call resize(0)
, it calls pop_back()
until every element is removed from the vector.
It doesn't matter that you moved vec
, because even though the state of vec
is unspecified, it is still a valid vector that you can modify.
So, the std::vector
will be empty after a call to resize(0)
.
After having moved from an object, you can generally not make any assumptions about the object's state. That means that you can only call member functions that do not have any preconditions. Happily, std::vector::resize
does not have value-dependent preconditions, so you can call resize
on a moved-from vector.