【问题标题】:C++ error: passing ‘const umap_int {aka const std::unordered_map<int, int>}’ as ‘this’ argument discards qualifiers [-fpermissive]C++ 错误:将“const umap_int {aka const std::unordered_map<int, int>}”作为“this”参数传递会丢弃限定符 [-fpermissive]
【发布时间】:2019-07-10 06:23:38
【问题描述】:

我正在尝试通过 unordered_map 的映射值的方法获取常量引用。 unordered_map 是一个类成员。但是,下面的代码不起作用并引发标题中所述的错误。

我尝试将 const umap_int::mapped_type &amp; 更改为 const int &amp; 也不起作用。返回对简单数据类型(int、double、...)变量的 const 引用的标准示例有效。

#include <unordered_map>

using namespace std;

typedef unordered_map<int, int> umap_int;

class class_A{

    public:

    class_A(){
        for(int k=0; k<3;++k)
            M[k] = k;
    }

    const umap_int::mapped_type & get_M(int key) const{
        return M[key];
    }

    private:

    umap_int M;

};

int main(){

    class_A A;

    return 0;
}

【问题讨论】:

  • 请不要调用成员变量M

标签: c++ reference constants return-value member-functions


【解决方案1】:

在 const 方法中你只能调用 M 它的 const 成员函数。 unordered_map::operator[] 的两个重载都是 非常量 - reference。所以你不能在 const get_M 中使用它。您可以从 get_M 签名中删除 const 限定符,或者使用具有 const 重载的 find,但是当传递的键不存在映射值时,您需要处理这种情况:

const umap_int::mapped_type & get_M(int key) const {
    //return M[key];
    auto it = M.find(key);
    if (it != M.end())
        return it->second;
    // do sth here ...
    // throw exception
    // make static variable with default value which will be accessed 
}

【讨论】:

  • 或有最小的改变:mutable umap_int M; 并且不要改变功能
  • 是的,这可能是另一种解决方案,但是 OP 应该添加 mutex 以保护对 M 集合的访问。如果我们假设 const 方法只读取数据,我们可以在许多线程中使用它们。如果没有互斥锁,我们将在通过opearator[] 访问地图时发生数据争用 - 它会在密钥不存在时添加新项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
相关资源
最近更新 更多