gpt4 book ai didi

c++ - std::terminate 和空容器的析构函数

转载 作者:行者123 更新时间:2023-11-28 00:07:32 25 4
gpt4 key购买 nike

考虑一些使用动态内存(即 AllocatorAwareContainer )并且大小和容量为零的标准容器。例如,取一个 std::vector 并调用 vec.resize(0); vec.shrink_to_fit();.

我可以想象这样的容器实例将只包含用于其逻辑内容的 nullptr 指针和用于跟踪信息的 std::size_t 成员 size。我还可以想象他们的析构函数基本上什么都不做,因为没有要释放的动态内存。

据我所知,容器的所有析构函数都是noexcept。 IE。在销毁过程中抛出异常时,它们应该调用 std::terminate。在 Allocator::deallocate() 抛出异常的情况下是可能的。

我能确定处于上述状态的容器永远不会在销毁时调用 std::terminate 吗?

最佳答案

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

不,不是。 Allocator 的要求禁止deallocate 抛出。它不是正式的 noexcept 说明符,但 C++14 表 28 分配器要求说:

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

因此,如果您的分配器在重新分配时抛出异常,这就违反了所需的契约(Contract),无论如何所有的赌注都会被取消。

关于c++ - std::terminate 和空容器的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34674604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com