开发者

C++: pass-by-reference and the const keyword

开发者 https://www.devze.com 2023-01-08 06:50 出处:网络
I have a question regarding the passing of a map by reference. Let\'s consider the following piece of codes:

I have a question regarding the passing of a map by reference. Let's consider the following piece of codes:

void doNotChangeParams(const map<int, int>& aMap){

    if (aMap.find(0) != aMap.end()){
        cout << "map[0] = " << aMap[0] << endl;
    }
}

and I'm having a map myMap and make a call like this: doNotChangeParams(myMap)

Now, it can be seen that I'm not modifying the parameter aMap inside the function. Nevertheless my g++ compiler complains that the access aMap[0] discards the qualifier const.

I'm putting const since I want to both tell re开发者_如何学Caders of this function that I'm not modifying the argument. Also, it helps throws compile errors when I accidentally modify the map.

Currently, I have to drop the const and I think it would make the above meaning unclear to the reader from the signature of the method. I know a comment would do, but I figure I would just ask in case you know of any "programmatic" ways.

Thanks, guys.


The [] operator on std::map is non-const. This is because it will add the key with a default value if the key is not found. So you cannot use it on a const map reference. Use the iterator returned by find instead:

typedef map<int, int> MyMapType;

void doNotChangeParams(const MyMapType& aMap){
    MyMapType::const_iterator result = aMap.find(0);
    if (result != aMap.end()){
        cout << "map[0] = " << result->second << endl;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消