Reputation: 105
Consider a std::vector
:
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
Would vec.clear()
and vec = std::vector<int>()
do the same job? What about the deallocation in second case?
Upvotes: 8
Views: 9101
Reputation: 238461
They are different:
clear
is guaranteed to not change capacity.
Move assignment is not guaranteed to change capacity to zero, but it may and will in a typical implementation.
The clear
guarantee is by this rule:
No reallocation shall take place during insertions that happen after a call to
reserve()
until the time when an insertion would make the size of the vector greater than the value ofcapacity()
Post conditions of clear
:
Erases all elements in the container. Post:
a.empty()
returnstrue
Post condition of assignment:
a = rv;
a shall be equal to the value that
rv
had before this assignment
a = il;
Assigns the range
[il.begin(),il.end())
into a. All existing elements of a are either assigned to or destroyed.
Upvotes: 5
Reputation: 36513
vec.clear()
clears all elements from the vector, leaving you with a guarantee of vec.size() == 0
.
vec = std::vector<int>()
calls the copy/move(Since C++11) assignment operator , this replaces the contents of vec
with that of other
. other
in this case is a newly constructed empty vector<int>
which means that it's the same effect as vec.clear();
. The only difference is that clear()
doesn't affect the vector's capacity while re-assigning does, it resets it.
The old elements are deallocated properly just as they would with clear()
.
Note that vec.clear()
is always as fast and without the optimizer doing it's work most likely faster than constructing a new vector and assigning it to vec
.
Upvotes: 14