Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can vector<T>::clear throw?

Is there any chance for a call to std::vector<T>::clear() to throw an exception?

like image 648
smallB Avatar asked Nov 09 '11 13:11

smallB


People also ask

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Does vector clear change capacity?

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.

Does vector clear deallocate memory?

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.

How do you clear a vector vector in C++?

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.


2 Answers

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: [..] — no erase(), clear(), pop_back() or pop_front() function throws an exception. [..]


What happens if my element type destructor throws?

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) [..]

like image 60
Lightness Races in Orbit Avatar answered Oct 04 '22 19:10

Lightness Races in Orbit


Yes, if the destructor of T throws, otherwise no.

Update: seems i was dead wrong; it just crashes in that case

like image 29
Viktor Sehr Avatar answered Oct 04 '22 19:10

Viktor Sehr