Reputation: 17128
Is there any chance for a call to std::vector<T>::clear()
to throw an exception?
Upvotes: 19
Views: 2798
Reputation: 13099
Yes, if the destructor of T
throws, otherwise no.
Update: seems i was dead wrong; it just crashes in that case
Upvotes: 5
Reputation: 385264
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) [..]
Upvotes: 24
Reputation: 12943
Yes and No
Yes:
clear
eventually calls delete[]
operator, which involves calling destructors of all the objects an the array (if they have one) and free
the memory.
Destructors may eventually throw an exception.
Memory freeing may also fail in abrnormal cases (such as heap corruption or etc.)
No:
Throwing exceptions is destructors is criticized and mostly doesn't happen (at least in the standard libraries). Besides the fact that exception thrown from a destructor during the stack unwinding (caused by another exception) may not be handled, there is a logical problem with exceptions in destructors.
Error in freeing memory usually caused by heap corruption or other unrecoverable problem. Anyway the program's fate is to die, no matter if there'll be exception or not
Upvotes: -2