Raedwald
Raedwald

Reputation: 48682

Can the std::vector default constructor throw an exception

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)?

Upvotes: 8

Views: 2309

Answers (1)

songyuanyao
songyuanyao

Reputation: 172964

It depends on the default constructor of Allocator. The default constructor of std::vector is declared as

vector() noexcept(noexcept(Allocator())); (since C++17)

And if 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.

Upvotes: 16

Related Questions