有人可以告诉我为什么这段代码会产生错误吗?
#include <iostream>
#include <map>
#include <vector>
#include <thread>
#include <mutex>
#include <stdexcept>
using namespace std;
void thread_func(const std::map<string, int>& shared) {
for (int i = 0; i < 10000; ++i) {
if (shared["what"] != 2 || shared["when"] != 4) {
throw std::logic_error("not read safe");
}
}
}
int main() {
std::map<string, int> shared;
shared["what"] = 2;
shared["when"] = 4;
vector<thread> threads;
for (int i = 0; i < 100; ++i) {
threads.push_back(thread(thread_func, shared));
}
for (auto& th : threads) {
th.join();
}
return 0;
}
这会产生以下错误
error: passing ‘const std::map<std::basic_string<char>, int>’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = std::basic_string<char>; _Tp = int; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, int> >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = std::basic_string<char>]’ discards qualifiers [-fpermissive]
if (shared["what"] != 2 || shared["when"] != 4) {
有人可以指导我正确的方向吗?
由于
答案 0 :(得分:4)
std::map::operator[]
可以在插入参数键时修改映射(如果尚未存在),因此不能在常量对象上调用。
改为使用std::map::at()
。