Now, I understand the reasoning here. After all:
#include <map>
#include <iostream>
using namespace std;
class A {
map<int, int> m;
public:
map<int, int> m;
public:
void foo(int i) const { cout << m[i] << endl; }
};
int main(int argc, char* argv[]) {
A a;
a.foo(42); // what happens here?
return 0;
}
};
int main(int argc, char* argv[]) {
A a;
a.foo(42); // what happens here?
return 0;
}
Our mythical const version of operator[] can't return a reference, as there's no object to refer to. It can't return a default value, either; there's no guarantee that the map's value type will have a default constructor (though in this case, the type int defaults to 0).
On the other hand, why not simply do as std::vector::operator[] does, and throw the programmer in the deep end if they access an invalid index? Thoughts? Comments? Heated counterarguments?
No comments:
Post a Comment