C++ unordered_map::at() 和运算符 [ ] 的行为不同

C++ unordered_map::at() and operator[ ] doesn't behave the same

本文关键字:运算符 unordered map at C++      更新时间:2023-10-16

我有以下代码

  unordered_map<unique_ptr<Test>, int> _unordered_map;
  Test* _test1 = new Test;
  unique_ptr<Test> _ptr0(_test1);
  unique_ptr<Test> _ptr1(new Test);
 _unordered_map.insert(make_pair( std::move(_ptr0), 1  ));
 _unordered_map.insert(make_pair( std::move(_ptr1), 1  ));
  unique_ptr<Test> _ptr3(_test1);
  cout <<  _unordered_map.at(_ptr3);

如果我将最后一行更改为,gcc会给出编译错误

cout <<  _unordered_map[_ptr3];

undered_map的运算符[]和at((的行为难道不应该相同吗?

unordered_mapoperator[]at()不应该表现相同吗?

没有。如果找不到键,则at将抛出异常,而[]将插入具有该键的新元素。为了做到这一点,提供的密钥必须是可复制的或可移动的;您的密钥类型是不可复制的,并且只有在作为右值传递时才可移动。所以这应该编译:

cout << _unordered_map[std::move(_ptr3)];

当然,使用[]at没有什么意义,因为您不能使一个非空的unique_ptr与映射中的任何一个进行比较(除非像您的示例中那样,创建两个拥有相同对象的unique_ptr,这将是灾难性的(。