访问成员unordered_map中的数据时,C++const方法在结构中编译错误
C++ const method compile error in struct when accessing data in member unordered_map
我不明白我遇到的编译错误。下面是我的用例的一个简化示例。
#include <unordered_map>
#include <iostream>
#using namespace std;
struct C{
unordered_map<int, string> m;
C(){
m[1] = "one";
m[2] = "two";
}
int method() const{
const string s = m[2];
return 42;
}
};
int main() {
C c;
cout << c.method() << endl;
return 0;
}
以下是我的用例要求:
- 我希望方法
method()
为const
,因为我确信它不会更改任何成员字段 - 由于频繁的数据访问,成员字段
m
应该是unordered_map
(或任何哈希表)
以上代码无法使用error: passing ‘const std::unordered_map<int, std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive]
进行编译。但是,如果我从方法method()
中删除const
(我不想或不能这样做),代码编译得很好。我有什么不明白的?在我的用例中,是否没有办法使方法const
?
顺便说一句,我在Ubuntu 15.10上使用GCC 5.2.1和CLion 1.2.4。
std::unordered_map::operator[]
不是const
方法,因为它在不存在元素的情况下插入元素。所以你不能在常数m
上使用它。使用
std::unordered_map::at
相反。
相关文章:
- 如何在声明为 const 的方法中更改类成员
- 具有参数 (const T *&) 或 (T * &) 或 (const T * const &) 或 (T * const &) 的方法
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- MSVC使用constexpr-if从可变模板方法中的基本模板参数中吞下const
- const_cast const 方法中的"this"将"this"分配给外部变量?
- 初始化 const 成员的正确方法
- const 方法使用引用修改对象
- 从类方法返回 "const char*" 作为 std::string&
- 从"wcslen"替换到"strnlen_s"时,用"const char*"进行类型转换是正确的方法吗?
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- 为什么 constexpr 假设我的方法就是 const
- 正确的方法通过巨大的const对象的向量
- 使用静态方法初始化 const 类字段的做法是好是坏
- c++应该对参数值类型的方法使用const
- 是否可以让C++方法接受const char*和const wchar_t*作为参数而不重载该方法
- 在非常量对象上,为什么C++不调用具有 public-const 和私有-nonconst 重载的方法的 const 版本?
- 如何使类的方法为const
- 我是否应该声明任何可以为const的方法为const方法?