std ::空容器的终止和析构函数 [英] std::terminate and destructors of empty containers

查看:149
本文介绍了std ::空容器的终止和析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑使用动态记忆体的标准容器(例如: AllocatorAwareContainer )并且具有零的大小和容量。例如,取一个 std :: vector 并调用 vec.resize(0);我想象这样的容器实例将只包含 nullptr $ c>其逻辑内容的指针和 std :: size_t 成员来跟踪信息,如 size 。我还想象他们的析构函数基本上什么也不做,因为没有动态的内存可以释放。



我知道,容器的所有析构函数都是 noexcept 。也就是说在销毁期间抛出异常,它们应该调用 std :: terminate 。在 Allocator :: deallocate()抛出异常的情况下是可能的。



状态,上述,在销毁时从不调用 std :: terminate

解决方案

blockquote>

有可能在 Allocator :: deallocate()抛出异常。


不,不是。 Allocator forbid deallocate 的要求。它不是一个正式的 noexcept 说明符,但是C ++ 14表28分配器要求说:


a.deallocate(p,n)[...]不抛出异常。


重新分配,这是违反所需的合同,所有投注都关闭。


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?

解决方案

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.

这篇关于std ::空容器的终止和析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆