C++编程常见问题—error: passing 'const std::map<>]' discards qualifiers或pass-by-reference-to-const-map导致的“d
2016-06-23 15:31
537 查看
产生问题的场景:
或者
int Test::func()const
{
string value = amap[0]; //amap是Test类的成员函数.
}
用g++编译上面的代码,会报……discards qualifiers。
这里是原因。
简单来说,map的[]运算符会在索引项不存在的时候自动创建一个对象,有可能会改变map本身,所以不能够用在一个const map上。
解决办法有两个:
方法1、不要将形参声明为const
方法2、用find代替[]
不过第二中方法存在风险,因为end()->second是合法的,于是就会产生传说中的null引用。
int func(const map<int, string> &aMap) {
string value = amap[0]; }
或者
int Test::func()const
{
string value = amap[0]; //amap是Test类的成员函数.
}
用g++编译上面的代码,会报……discards qualifiers。
这里是原因。
简单来说,map的[]运算符会在索引项不存在的时候自动创建一个对象,有可能会改变map本身,所以不能够用在一个const map上。
解决办法有两个:
方法1、不要将形参声明为const
方法2、用find代替[]
不过第二中方法存在风险,因为end()->second是合法的,于是就会产生传说中的null引用。
相关文章推荐
- JS命名规范
- Node.js学习1-创建第一个应用
- node.js中的path对象
- angularjs中使用ng-repeat需要注意的东西
- 前端性能优化知识,包括css和js
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- firstChild.nodeValue 和 lastChild.nodeValue
- css3属性-webkit-font-smoothing