Search code examples
c++c++11stlnoexceptexception-safety

std::terminate and destructors of empty containers


Consider some standard container which uses dynamic memory (i.e. is an AllocatorAwareContainer) and has a size and capacity of zero. For example, take a std::vector and call vec.resize(0); vec.shrink_to_fit();.

I would imagine that such container instances would contain only nullptr pointers for their logical contents and std::size_t members to track information like size. I would also imagine that their destructors would do essentially nothing, as there is no dynamic memory to be freed.

All destructors of containers, as I know, are noexcept. I.e. on throwing of an exception during destruction they should call std::terminate. It is possible in case of Allocator::deallocate() throw exception.

Can I be sure containers in the state, described above, never call std::terminate on destruction?


Solution

  • It is possible in case of Allocator::deallocate() throw exception.

    No, it's not. The requirements for Allocator forbid deallocate to throw. It's not a formal noexcept specifier, but C++14 Table 28 Allocator requirements says:

    a.deallocate(p, n) [...] Does not throw exceptions.

    So if your allocator throws on deallocation, that's a violation of the required contract and all bets are off anyway.