Can the default constructor of std::list<int> throw?

百般思念 提交于 2020-01-14 12:46:07

问题


I had a (quick) look into the C++ standard and into an online C++ reference, but I could not find an answer to this simple question:

Can the default constructor of std::list<int> throw?

If so, why would it throw?


回答1:


Short answer: it can, but it may be implemented in a way that is reasonably safe:

The default constructor constructs an empty list, so there is little need to actually allocate memory in the process. Most list implementations won't allocate any memory for an empty list.

However, the default constructor is not really a default constructor, since it has a defaulted argument: explicit list(const Allocator& = Allocator());
Allocator itself is a template argument, so the call of the constructor already might throw, if Allocator has a sufficiently dumb (or complex) implementation providing a throwing default constructor, i.e. if the construction of the default argument throws.

If the default constructor of Allocator does not throw, it is realtively easy to provide an implementation of std::list whose default constructor won't throw either. But library implementors are not required to do so.

Updated: The list has to store a copy of the given allocator to be able to call it later. Contrary to my prior claim, the resulting call to the copy constructor of Allocator may not throw (§17.6.3.5, see the comments). The list implementation is also not allowed to e.g. default-construct the allocator and do a copy assignment in the constructor, because that would break any code that tries to use the list with allocators that are not default-constructible.




回答2:


The C++11 standard declares the list's default constructor as

explicit list(const Allocator& = Allocator());

, which does not include a noexcept. Thus, the standard implicitly allows it to throw exceptions.




回答3:


It may potentially allocate space via new to create its internal structure, so yes, it may possibly throw.



来源:https://stackoverflow.com/questions/19930011/can-the-default-constructor-of-stdlistint-throw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!