c++ - 为什么 STL 容器中的交换成员函数没有声明为 noexcept?

标签 c++ c++11 swap noexcept

截至 N3797 C++ 标准要求容器的 swap 函数不抛出任何异常,除非另有说明[container.requirements.general](23.2.1§10 )。

  • 为什么swap成员函数被指定不抛出未声明的noexcept

同样的问题也适用于专门的非成员 swap 重载。

最佳答案

进一步到what refp said ,这是 Daniel Krügler 在 std-discussion 邮件列表上的帖子:

The internal policy to declare a function as unconditional noexcept is explained in

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3279.pdf

With the terminology used in that paper, std::vector's swap function has a narrowing contract, that is it has preconditions in regard to the allocators of the participating objects. This means, there exists the possibility that callers may violate the preconditions and an implementation should be allowed to signal this my different means than by termination. Therefore such functions should not be noexcept, but it should have an effective element "Throws: Nothing" because this applies to the situation when the preconditions are satisfied.

( link )

上述内部政策是对您问题的规范、官方回答。

关于c++ - 为什么 STL 容器中的交换成员函数没有声明为 noexcept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754223/

相关文章:

algorithm - 如何在 O(n^2) 时间内找到冒泡排序中预期交换的数量

c++ - 库设计 : Hiding dependencies

c++ - 在 C++ 中将 Double 转换为 String

C++ 模板元程序。条件内存分配

c++ - 删除修饰符与将函数声明为私有(private)

memory - 使用 ansible 添加交换内存

c++ - 这是否符合尾递归的条件?

c++ - 通过范围循环从指针容器中获取取消引用元素的引用

c++ - 为可变函数设计更好的 API

php - 我可以使用 PHP 中的 GD 库交换图像中的颜色吗?