Is there any chance for a call to std::vector<T>::clear()
to throw an exception?
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
The standard mandates that the capacity does not change with a clear as reserve guarantees that further adding of elements do not relocate until the requested capacity is reached. This directly enforces clear to not reduce the capacity.
No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory. Show activity on this post.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
No.
[2003: 21.2.1/11 | n3290: 21.2.1/10]:
Unless otherwise specified (see 23.2.4.1, 23.2.5.1, 23.3.3.4, and 23.3.6.5) all container types defined in this Clause meet the following additional requirements: [..] — noerase()
,clear()
,pop_back()
orpop_front()
function throws an exception. [..]
In C++11, std::vector<T>::clear()
is marked noexcept
([n3290: 23.3.6/1]
).
Any exceptions falling out of ~T
could be caught by the implementation, so that clear()
itself may not throw anything. If they're not, and it does, the exception is "unexpected" and terminates the process rather than propagating:
struct T {
~T() { throw "lol"; }
};
int main() {
try {
vector<T> v{T()};
v.clear();
}
catch (...) {
cout << "caught";
}
}
// Output: "terminated by exception: lol" (GCC 4.7.0 20111108)
[n3290: 15.5.1]:
In some situations exception handling must be abandoned for less subtle error handling techniques. [..] — when the search for a handler (15.3) encounters the outermost block of a function with a no-except-specification that does not allow the exception (15.4) [..]
Yes, if the destructor of T
throws, otherwise no.
Update: seems i was dead wrong; it just crashes in that case
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