std::terminate and destructors of empty containers

大兔子大兔子 提交于 2019-12-12 03:26:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34674604/stdterminate-and-destructors-of-empty-containers

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