加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么std :: unordered_map :: count上没有`noexcept`说明

发布时间:2020-12-16 10:01:43 所属栏目:百科 来源:网络整理
导读:我正在阅读关于std :: unordered_map的 C++ reference page.该 empty 和 size 方法不是合格的,但不是 count . 我不认为它应该算数. 我错过了什么吗? 解决方法 因为要求如此说: count返回与特定键匹配的元素数,并且对于任何无序关联容器类型X(实例化std ::
我正在阅读关于std :: unordered_map的 C++ reference page.该
emptysize方法不是合格的,但不是 count.

我不认为它应该算数.

我错过了什么吗?

解决方法

因为要求如此说:

count返回与特定键匹配的元素数,并且对于任何无序关联容器类型X(实例化std :: unordered_maps是此类容器),对X :: key_type类型的对象评估键比较

n3337 23.2.5 / 5 [unord.req]

Two values k1 and k2 of type Key are considered equivalent if the container’s key equality predicate returns true when passed those values. … For any two keys k1 and k2 in the same container,callingpred(k1,k2) shall always return the same value. …

对于无序映射,X :: key_type被定义为其模板参数列表的一部分:

template<
    class Key,//    ^^^ member type key_type set from this parameter
    class T,class Hash = std::hash<Key>,class KeyEqual = std::equal_to<Key>,//    ^^^^^^^^ member type key_equal set from this parameter
    class Allocator = std::allocator< std::pair<const Key,T> >
> class unordered_map;

我可以在key_type上找到的唯一约束也适用于value_type:

n3337 23.2.5 / 9 [unord.req] 2

… the requirements placed on value_type in Table 96 apply instead to key_type and mapped_type.

所以我们只需要知道表96中对value_type的要求,它指定了Container的要求.在第一行中,我们有:

n3337,表963

X::value_type | Returns T | Requires: T is Destructible

其中X再次是Container的类型,T是它存储的对象的类型.可破坏对象不允许抛出析构函数.这是他们唯一的要求.

n3337,表24

u.~T() All resources owned by u are reclaimed,no exception is propagated

(你是符合Destructible要求的T型对象)

因此,对unordered_map的密钥比较函数提供的抛出保证没有限制,因此不保证std :: equal_to提供的operator ==操作实现所需的行为.密钥本身没有任何这样的限制,因此:允许比较函数抛出,并且允许使用比较函数的任何函数抛出. count需要使用与提供的键匹配的键和比较函数来计算存储的值,因此它可能会抛出.

clear可能是noexcept,因为标准禁止抛出析构函数:

17.6.4.8 / 1,24 [res.on.functions]

In certain cases (replacement functions,handler functions,operations on types used to instantiate standard library template components),the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements,the Standard places no requirements on the implementation.

In particular,the effects are undefined in the following cases:

  • if any replacement function or handler function or destructor operation exits via an exception,unless specifically allowed in the applicable Required behavior: paragraph.

由于唯一依赖于客户端的代码清除执行可能不会抛出异常,并且实现不需要,它可能已被标记为noexcept

笔记:

1. n4140标准草案(接近c 14)似乎根本没有改变这一条款.

2. n4140保留这一措辞,从第9条移至第10条.

3.容器要求也列在n4140的表96中,并列出了T为Erasable的要求,它也对操作符没有限制==

4.该条款的措辞在n4140中没有改变.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读