Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why vector's move ctor does not deduce a noexcept()?

Why move constructor for std::vector with custom allocator does not deduce a noexcept() from allocator's behaviours?

This leads to the class that encapsulates such vector cannot form the (other) vector that can be normally moved in some <algorithm>s. Even if the underlying type meets the nessesary requirements (MoveInsertable and DefaultInsertable).

like image 689
Tomilov Anatoliy Avatar asked Apr 22 '13 07:04

Tomilov Anatoliy


People also ask

Why should move constructor be Noexcept?

noexcept is nice for two reasons: The compiler can optimize a little better because it doesn't need to emit any code for unwinding a call stack in case of an exception, and. It leads to incredible performance differences at runtime for std::vector (and other containers, too)

Should copy constructor be Noexcept?

The copy constructor for an object thrown as an exception must be declared noexcept , including any implicitly-defined copy constructors.


1 Answers

I assume that by "move constructor for std::vector with custom allocator" you mean the allocator-extended move constructor i.e. this constructor:

vector(vector&& v, const allocator_type& a);

The main reason is that if v.get_allocator() != a then the constructor must allocate more memory, which could throw bad_alloc. There is no way to know at compile-time if two allocators of a given type will always compare equal or not (I have reported this as a defect, see LWG 2108).

N.B. the standard does not require this constructor or the vector(vector&&) move constructor to be noexcept.

like image 157
Jonathan Wakely Avatar answered Sep 29 '22 02:09

Jonathan Wakely