我注意到
std::vector
容器的交换函数具有与所有其他容器不同的 noexcept 规范。具体来说,如果表达式
std::allocator_traits<Allocator>::propagate_on_container_swap || std::allocator_traits<Allocator>::is_always_equal
为 true,但其他容器要求表达式 std::allocator_traits<Allocator>::is_always_equal
为 true。
既然交换函数的行为是相同的,为什么仅在
std::vector
容器中的 noexcept 规范不同?
std::allocator_traits<Allocator>::propagate_on_container_swap
确定容器是否可交换。如果发现它不是 swappabe,则将 propagate_on_container_swap
指定为 noexcept
条件只会增加语法噪音。
另一方面,std::vector
和 std::string
系列是上述规则的例外(由于它们是连续分配的??)。这些容器的可交换性通常是在运行时确定的。即使 propagate_on_container_swap
为 false,他们也会尝试交换,但如果为 true,则不会抛出异常。