gpt4 book ai didi

c++ - std::map 的 const_cast 问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:32:59 25 4
gpt4 key购买 nike

我最近遇到了一个问题,我能看到避免它的唯一方法是使用 const_cast - 但我猜我没有想到有一种方法可以在不改变代码功能的情况下避免这种情况。下面的代码片段将我的问题提炼成一个非常简单的示例。

struct Nu
{
Nu() {v = rand();}
int v;
};

struct G
{
~G()
{
for(auto it = _m.begin(); it != _m.end(); it++) delete it->first;
}
void AddNewNu()
{
_m[new Nu] = 0.5f;
}
void ModifyAllNu()
{
for(auto it = _m.begin(); it != _m.end(); it++) it->first->v++;
}
float F(const Nu *n) const
{
auto it = _m.find(n);
// maybe do other stuff with it
return it->second;
}

map<Nu*, float> _m;
};

在这里,假设 Nu 实际上是一个非常大的结构,其布局已经由匹配外部库的需要固定(因此“ float ”不能简单地折叠到 Nu 中,并且由于各种其他原因它不能'不是 map<Nu, float> )。 G 结构有一个映射,用于保存它创建的所有 Nu(并最终在销毁时将它们全部删除)。如所写,函数 F 将无法编译 - 它无法按照 std::map 的预期将 (const Nu *n) 转换为 (Nu n)。但是 map 不能切换到map<const Nu*, float>因为有些非常量函数还是需要修改_m里面的Nu的。当然,我也可以将所有这些 Nu 存储在一个额外的 std::vector 中,然后将映射类型切换为 const - 但这引入了一个完全不必要的 vector 。所以目前我想到的唯一选择是在 F 函数中使用 const_cast(这应该是一个安全的 const_cast),我想知道这是否可以避免。

经过更多的搜索后,这个完全相同的问题已经在这里得到解决:Calling map::find with a const argument

最佳答案

这是因为 map 需要 Nu* const,但您已经给它一个 const Nu*。我也觉得这很不合逻辑,不明白为什么,但事实就是如此。

关于c++ - std::map 的 const_cast 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com