If I construct an empty
std::vector using the default constructor (and the default allocator), can it throw an exception?
In general, allocating space for the elements of a container can throw an exception (which would be a
std::bad_alloc). But the default constructor of a
std::vector does not need to allocate any such space; it can lazily allocate some space on the first insertion or assignment. But does the C++ standard require that it does not throw exceptions (implying lazy allocation, or catching
std::bad_alloc and then falling back to lazy allocation)?
It depends on the default constructor of
Allocator. The default constructor of
std::vector is declared as
vector() noexcept(noexcept(Allocator())); (since C++17)
std::allocator is used then it's
noexcept(true); i.e. won't throw exceptions.
allocator() noexcept; (since C++11)
Hence, before C++17, or if using a non-default allocator, throwing exceptions is possible.