简体   繁体   English

std :: vector默认构造函数是否可以抛出异常

[英]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? 如果我使用默认构造函数(和默认分配器)构造一个空的std::vector ,它会抛出异常吗?

In general, allocating space for the elements of a container can throw an exception (which would be a std::bad_alloc ). 通常,为容器元素分配空间可能会抛出异常(这将是一个std::bad_alloc )。 But the default constructor of a std::vector does not need to allocate any such space; 但是std::vector的默认构造函数不需要分配任何这样的空间; 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)? 但是C ++标准是否要求它不会抛出异常(暗示延迟分配,或者捕获std::bad_alloc然后再回到延迟分配)?

It depends on the default constructor of Allocator . 它取决于Allocator的默认构造函数。 The default constructor of std::vector is declared as std::vector的默认构造函数声明为

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

And if std::allocator is used then it's noexcept(true) ; 如果使用std::allocator那么它是noexcept(true) ; ie won't throw exceptions. 即不会抛出异常。

 allocator() noexcept; (since C++11) 

Hence, before C++17, or if using a non-default allocator, throwing exceptions is possible. 因此,在C ++ 17之前,或者如果使用非默认分配器,则可以抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM