这个问题可能更适合一般的C++,但是由于我在Linux上使用gcc,因此这是上下文。
考虑以下程序:
当执行程序时,输出结果为:
我希望编译器在第二次调用时选择
我期望的行为类似于C#索引运算符,它具有get和set操作,您可以在getter尝试访问不存在的内容时抛出异常。
因此,我想知道为什么gcc在不需要非const访问时更喜欢非const调用而不是const调用。
#include <iostream>
#include <map>
#include <string>
using namespace std;
template <typename TKey, typename TValue>
class Dictionary{
public:
map<TKey, TValue> internal;
TValue & operator[](TKey const & key)
{
cout << "operator[] with key " << key << " called " << endl;
return internal[key];
}
TValue const & operator[](TKey const & key) const
{
cout << "operator[] const with key " << key << " called " << endl;
return internal.at(key);
}
};
int main(int argc, char* argv[])
{
Dictionary<string, string> dict;
dict["1"] = "one";
cout << "first one: " << dict["1"] << endl;
return 0;
}
当执行程序时,输出结果为:
operator[] with key 1 called
operator[] with key 1 called
first one: one
我希望编译器在第二次调用时选择
operator[]const
方法。原因是,如果之前没有使用过dict["1"],调用operator[]
会导致内部映射创建不存在的数据,即使我只想进行一些调试输出,这当然是致命的应用程序错误。我期望的行为类似于C#索引运算符,它具有get和set操作,您可以在getter尝试访问不存在的内容时抛出异常。
class MyDictionary<TKey, TVal>
{
private Dictionary<TKey, TVal> dict = new Dictionary<TKey, TVal>();
public TVal this[TKey idx]
{
get
{
if(!dict.ContainsKey(idx))
throw KeyNotFoundException("...");
return dict[idx];
}
set
{
dict[idx] = value;
}
}
}
因此,我想知道为什么gcc在不需要非const访问时更喜欢非const调用而不是const调用。