I have a map that is part of an object that I want to make sure that I never accidentally mess up; however, when compiling, I get the following error:
./test.cpp: In member function ‘std::map<int, mapValue>& myClass::getMap() const’:
./test.cpp:22:49: error: binding reference of type ‘std::map<int, mapValue>&’ to ‘const std::map<int, mapValue>’ discards qualifiers
22 | map<key, mapValue> &getMap() const { return m; }
|
Here is my code:
#include <string>
#include <map>
#include <iostream>
using namespace std;
struct mapValue
{
int num;
string data;
};
class myClass
{
public:
typedef int key; //hopefully this helps future people searching for a similar error
void adjustMap(int index, mapValue mv)
{
m[index] = mv;
}
map<key, mapValue> &getMap() const { return m; }
private:
map<key, mapValue> m = {
{0, {0, "Hi!"}},
{1, {0, "Hello"}},
{2, {1, "Goodbye"}}
};
};
void operateWithMapData(const myClass &c) //I don't want to accidentally mess up
//the map or anything in c
{
const auto &m = c.getMap(); //Seriously, I do NOT want to edit this map.
for(auto &kv : m)
{
cout << kv.first << ":" << kv.second.data << ":" << kv.second.num << endl;
}
}
int main()
{
myClass c;
c.adjustMap(5, {8, "Bye"});
operateWithMapData(c);
return EXIT_SUCCESS;
}
I want to make sure that when I’m working on operateWithMapData
that I don’t accidentally insert, change, or delete any existing values.
Normally, I know that when I make c
a const reference, then I’m not:
- pointlessly coping over large amounts of data (pass by reference part)
- making it immutable (the const part)
If I were to just do that and remove const from myClass::getMap()
and leave it in operateWithMapData
then:
- It still doesn’t compile
- That could mean I have access to a mutable version of the raw map that I could screw up somewhere else.
I guess my question is two parts:
- How do I correctly accomplish what I want to?
- Can I get a good detailed explanation on what this error means so if I see something like it in the future, then I can fix it on my own.
Here are some related questions, but I don’t think they solve my problem..
Binding to reference of type discards qualifiers
How to return a class object by reference in C++?
Error: Binding reference of type ‘&’ to ‘const discards qualifiers’
2