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?
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
.
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.
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