问题
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