【发布时间】:2018-06-05 17:20:47
【问题描述】:
我观察到 std::map::const_iterator 泄漏了对 value_type 的非常量引用:
#include <map>
#include <stdio.h>
int main (int argc, char *argv[])
{
std::map<int,int> foo = {{1,1},{4,2}};
const auto &m = foo;
const auto &it = foo.find(1);
printf("%d %d\n", it->first, it->second);
int &i = it->second;
i = 3;
auto &one = foo.at(1);
printf("%d %d\n", 1, one);
return 0;
}
输出
$ g++ test.cc && ./a.out
1 1
1 3
这是预期的吗?为什么?编码 std::map 的 const 保护的唯一方法是将其包装在另一个类中吗?
【问题讨论】:
-
是什么让你认为你在使用 const_iterator?
-
foo.find(1)返回一个迭代器。也许你打算写m.find(1)(它确实返回一个const_iterator,因此会产生编译错误) -
噢!谢谢@UnholySheep。这就是问题所在。