Ash*_*ain 5 c++ stl const-correctness map
请考虑以下代码段:
#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;
}
Run Code Online (Sandbox Code Playgroud)
错误f()
是由于map的const重载引起find()
的const KeyType&
.因为地图的关键类型是int*
,所以转入int* const
. f()
采用一个const int&
参数,这是正确的,因为从不修改参数.
不幸的是,最终会尝试将a转换const int*
为a int* const
,它会丢失int上的const限定符并且不会编译.
这有点令人生气,因为参数绝对不会被修改 - 它只是用于find() - 但我仍然需要const_cast
它.
有没有办法写f()
没有const_cast
?
你可以改变map
to 的类型std::map<const int*, int>
; 不过,我怀疑你是否需要指针作为键.正如詹姆斯指出的那样,关键类型应该是const int*
因为你永远不打算通过改变指示物map
.如果你这样做,我会更加担心.
真正的问题是:为什么地图的索引不是指向const的指针?(当然,假设它应该是一个指针.)你真的希望能够通过类似的东西修改索引吗*myMap.find(&x)->first = xxx
?我会说这很不寻常,因为你已经有了一个指向对象的指针.