C++:为什么gcc在访问operator []时更喜欢非const over const?

Jon*_*asW 7 c++ gcc const

关于C++,这个问题可能更适合问题,但是因为我在linux上使用gcc就是上下文.考虑以下程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

执行程序时,输出为:

   operator[] with key 1 called 
   operator[] with key 1 called 
   first one: one
Run Code Online (Sandbox Code Playgroud)

我想要的是让编译器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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,我想知道为什么当不需要非const访问时,gcc更喜欢对const调用的非const调用.

Gab*_*yer 0

如果您实例化该类的 const 对象,它将使用 const 方法。