Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call vector.resize(0) after moving its content [duplicate]

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
like image 693
user1235183 Avatar asked Jun 07 '16 15:06

user1235183


1 Answers

Yes, it is safe.

From §23.3.6.5:

If sz <= size(), equivalent to calling pop_back() size() - sz times. If size() < sz, appends sz - 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).

like image 150
Rakete1111 Avatar answered Oct 06 '22 16:10

Rakete1111