c++ - 被 const 逼入绝境:std::map::find() const 重载

标签 c++ stl map const-correctness

考虑以下片段:

#include <map>

class C {
public:
    C() {}

    const int& f(const int& x) const
    {
        // Error: cannot cast const int* to int* const
        return myMap.find(&x)->second;

        // With a const_cast works:
        //return myMap.find(const_cast<int* const>(&x))->second;
    }

    std::map<int*, int> myMap;
};

int _tmain(int argc, _TCHAR* argv[])
{
    int x = 0;

    C c;
    c.f(x);

    return 0;
}

f() 中的错误是由 map 的 find() 的 const 重载采用 const KeyType& 引起的。因为 map 的键类型是int*,所以这变成了int* constf() 接受一个 const int& 参数,这是正确的,因为该参数永远不会被修改。

不幸的是,这最终导致尝试将 const int* 转换为 int* const,这会丢失 int 上的 const 限定符并且无法编译。

这有点令人恼火,因为参数肯定从未被修改过 - 它只是用于 find() - 但我仍然需要 const_cast 它。

有没有办法不用 const_cast 来写 f()

最佳答案

您可以只更改 map 的类型至 std::map<const int*, int> ;不过,我质疑您是否首先需要指针作为键。正如詹姆斯指出的那样,关键类型应该是 const int*因为您从不打算通过 map 修改引用对象.如果你这样做,我会更担心。

关于c++ - 被 const 逼入绝境:std::map::find() const 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845212/

相关文章:

c++ - 获取指向迭代器引用的 STL 容器的指针?

c++ - 将 vector 作为数组传递是否安全?

c++ - 返回迭代器

scala - 如何避免 map 连接的奇怪顺序? (A++B++C ---> BAC)

java - 需要一些关于 Java 中的 Lambda 表达式的帮助

c++ - 使用类模板参数推导来制作静态接口(interface)

c++ - 名称查找和类范围

C++ 自定义异常

c++ - 我想我可能想出了一个数组类型右值的例子

java - 内存高效的多值映射