C++ unordered_map::at() 和运算符 [ ] 的行为不同
C++ unordered_map::at() and operator[ ] doesn't behave the same
我有以下代码
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_map
的operator[]
和at()
不应该表现相同吗?
没有。如果找不到键,则at
将抛出异常,而[]
将插入具有该键的新元素。为了做到这一点,提供的密钥必须是可复制的或可移动的;您的密钥类型是不可复制的,并且只有在作为右值传递时才可移动。所以这应该编译:
cout << _unordered_map[std::move(_ptr3)];
当然,使用[]
或at
没有什么意义,因为您不能使一个非空的unique_ptr
与映射中的任何一个进行比较(除非像您的示例中那样,创建两个拥有相同对象的unique_ptr
,这将是灾难性的(。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<